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

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


当前回答

extension StringExtension on String {
  String capitalize() {
    return this
        .toLowerCase()
        .split(" ")
        .map((word) => word[0].toUpperCase() + word.substring(1, word.length))
        .join(" ");
  }
}

对于感兴趣的人,这应该适用于任何字符串

其他回答

我已经使用汉娜斯塔克的答案,但它崩溃的应用程序,如果字符串是空的,所以这里是与扩展的解决方案的改进版本:

extension StringExtension on String {
  String capitalize() {
    if(this.length > 0) {
      return "${this[0].toUpperCase()}${this.substring(1)}";
    }
    return "";
  }
}
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!');
});

一些更流行的其他答案似乎不处理null和”。我更喜欢不必在客户端代码中处理这些情况,我只是想要一个字符串返回无论什么-即使这意味着一个空的情况下为null。

String upperCaseFirst(String s) => (s??'').length<1 ? '' : s[0].toUpperCase() + s.substring(1)
extension StringExtension on String {
  String capitalize() {
    return this
        .toLowerCase()
        .split(" ")
        .map((word) => word[0].toUpperCase() + word.substring(1, word.length))
        .join(" ");
  }
}

对于感兴趣的人,这应该适用于任何字符串

你可以用这个:

extension EasyString on String {
  String toCapitalCase() {
   var lowerCased = this.toLowerCase();
   return lowerCased[0].toUpperCase() + lowerCased.substring(1);
 }
}