我如何大写字符串的第一个字符,而不改变任何其他字母的情况?

例如,“this is a string”应该给出“this is a string”。


当前回答

String capitalize(String s) => (s != null && s.length > 1)
    ? s[0].toUpperCase() + s.substring(1)
    : s != null ? s.toUpperCase() : null;

它通过了测试:

test('null input', () {
  expect(capitalize(null), null);
});
test('empty input', () {
  expect(capitalize(''), '');
});
test('single char input', () {
  expect(capitalize('a'), 'A');
});
test('crazy input', () {
  expect(capitalize('?a!'), '?a!');
});
test('normal input', () {
  expect(capitalize('take it easy bro!'), 'Take it easy bro!');
});

其他回答

下面是代码,如果你想在一个句子中大写每个单词,例如,如果你想大写你客户的fullName的每个部分,你可以简单地在你的模型类中使用以下扩展:

extension StringExtension on String {
  String capitalizeFirstLetter() {
    return "${this[0].toUpperCase()}${this.substring(1).toLowerCase()}";
  }
}

只需使用这个getter

String get formalFullName =>  fullName.capitalizeFirstLetter().splitMapJoin(RegExp(r' '),
                onNonMatch: (str) => str.toString().capitalize());

希望这对大家有所帮助

有一个包含该函数的utils包。它有一些更好的方法来操作字符串。

安装方法:

dependencies:
  basic_utils: ^1.2.0

用法:

String capitalized = StringUtils.capitalize("helloworld");

Github:

https://github.com/Ephenodrom/Dart-Basic-Utils

把这个拷贝到某个地方:

extension StringCasingExtension on String {
  String toCapitalized() => length > 0 ?'${this[0].toUpperCase()}${substring(1).toLowerCase()}':'';
  String toTitleCase() => replaceAll(RegExp(' +'), ' ').split(' ').map((str) => str.toCapitalized()).join(' ');
}

用法:

// import StringCasingExtension

final helloWorld = 'hello world'.toCapitalized(); // 'Hello world'
final helloWorld = 'hello world'.toUpperCase(); // 'HELLO WORLD'
final helloWorldCap = 'hello world'.toTitleCase(); // 'Hello World'
String? toCapitalize(String? input) {
  if (input == null || input.isEmpty) return input;
  return '${input[0].toUpperCase()}${input.substring(1).toLowerCase()}';
}

或扩展:

extension StringExtension on String {
  String? toCapitalize() {
    if (this == null || this.isEmpty) return this;
    return '${this[0].toUpperCase()}${this.substring(1).toLowerCase()}';
  }
}

简单,没有任何扩展:

title = "some title without first capital"

title.replaceRange(0, 1, title[0].toUpperCase())

// Result: "Some title without first capital"