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

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


当前回答

你可以使用这个函数:

String capitalize(String str) {
  return str
      .split(' ')
      .map((word) => word.substring(0, 1).toUpperCase() + word.substring(1))
      .join(' ');
}

其他回答

这个代码适用于我。

String name = 'amina';    

print(${name[0].toUpperCase()}${name.substring(1).toLowerCase()});

把这个拷贝到某个地方:

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'
void main() {
  print(capitalize("this is a string"));
  // displays "This is a string"
}

String capitalize(String s) => s[0].toUpperCase() + s.substring(1);

查看在DartPad上运行的代码片段:https://dartpad.dartlang.org/c8ffb8995abe259e9643

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

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

如果您使用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