我如何大写字符串的第一个字符,而不改变任何其他字母的情况?
例如,“this is a string”应该给出“this is a string”。
我如何大写字符串的第一个字符,而不改变任何其他字母的情况?
例如,“this is a string”应该给出“this is a string”。
当前回答
String fullNameString =
txtControllerName.value.text.trim().substring(0, 1).toUpperCase() +
txtControllerName.value.text.trim().substring(1).toLowerCase();
其他回答
还应该检查字符串是空还是空。
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);
}
截至2021年3月23日,Flutter 2.0.2
只需使用yourtext.capitalizeFirst
有一个包含该函数的utils包。它有一些更好的方法来操作字符串。
安装方法:
dependencies:
basic_utils: ^1.2.0
用法:
String capitalized = StringUtils.capitalize("helloworld");
Github:
https://github.com/Ephenodrom/Dart-Basic-Utils
你可以用这个:
extension EasyString on String {
String toCapitalCase() {
var lowerCased = this.toLowerCase();
return lowerCased[0].toUpperCase() + lowerCased.substring(1);
}
}
你可以使用Text_Tools包,使用简单:
https://pub.dev/packages/text_tools
你的代码应该是这样的:
//This will print 'This is a string
print(TextTools.toUppercaseFirstLetter(text: 'this is a string'));