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

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


当前回答

var original = "this is a string";
var changed = original.substring(0, 1).toUpperCase() + original.substring(1);

其他回答

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

简单,没有任何扩展:

title = "some title without first capital"

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

// Result: "Some title without first capital"

你可以用这个:

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

把这个拷贝到某个地方:

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'

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

希望这对大家有所帮助