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

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


当前回答

在范围内检查。 成语作为Dart >2.16.1

作为一个函数

String capitalize(String str) =>
    str.isNotEmpty
        ? str[0].toUpperCase() + str.substring(1)
        : str;

作为延伸

extension StringExtension on String {
    String get capitalize => 
        isNotEmpty 
            ? this[0].toUpperCase() + substring(1) 
            : this;
}

其他回答

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

String upperCaseFirst(String s) => (s??'').length<1 ? '' : s[0].toUpperCase() + s.substring(1)

检查空字符串大小写,同样使用短符号:

  String capitalizeFirstLetter(String s) =>
  (s?.isNotEmpty ?? false) ? '${s[0].toUpperCase()}${s.substring(1)}' : s;

下面是代码,如果你想在一个句子中大写每个单词,例如,如果你想大写你客户的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());

希望这对大家有所帮助

如果您使用get: ^4.6.5作为flutter的状态管理,则有用于大写的内置扩展

        // This will capitalize first letter of every word
        print('hello world'.capitalize); // Hello World

        // This will capitalize first letter of sentence
        print('hello world'.capitalizeFirst); // Hello world

        // This will remove all white spaces from sentence
        print('hello world'.removeAllWhitespace); // helloworld

        // This will convert string to lowerCamelCase
        print('This is new world'.camelCase); // thisIsNewWorld

        // This will remove all white spaces between the two words and replace it with '-'
        print('This is new    world'.paramCase); // this-is-new-world

截至2021年3月23日,Flutter 2.0.2

只需使用yourtext.capitalizeFirst