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

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


当前回答

把这个拷贝到某个地方:

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 capitalize(String input) {
  if (input == null) {
    throw new ArgumentError("string: $input");
  }
  if (input.length == 0) {
    return input;
  }
  return input[0].toUpperCase() + input.substring(1);
}

final helloWorld = 'hello world'.toUpperCase(); 文本(helloWorld);

我发现的另一个不健康的解决这个问题的方法是

String myName = "shahzad";

print(myName.substring(0,1).toUpperCase() + myName.substring(1));

这将产生同样的效果,但这是一种相当肮脏的方式。

非常晚,但是我用,


String title = "some string with no first letter caps";
    
title = title.replaceFirst(title[0], title[0].toUpperCase()); // Some string with no...

这个代码适用于我。

String name = 'amina';    

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