我如何大写字符串的第一个字符,而不改变任何其他字母的情况?
例如,“this is a string”应该给出“this is a string”。
我如何大写字符串的第一个字符,而不改变任何其他字母的情况?
例如,“this is a string”应该给出“this is a string”。
当前回答
var original = "this is a string";
var changed = original.substring(0, 1).toUpperCase() + original.substring(1);
其他回答
String fullNameString =
txtControllerName.value.text.trim().substring(0, 1).toUpperCase() +
txtControllerName.value.text.trim().substring(1).toLowerCase();
final helloWorld = 'hello world'.toUpperCase(); 文本(helloWorld);
还应该检查字符串是空还是空。
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);
}
这个代码适用于我。
String name = 'amina';
print(${name[0].toUpperCase()}${name.substring(1).toLowerCase()});
有一个包含该函数的utils包。它有一些更好的方法来操作字符串。
安装方法:
dependencies:
basic_utils: ^1.2.0
用法:
String capitalized = StringUtils.capitalize("helloworld");
Github:
https://github.com/Ephenodrom/Dart-Basic-Utils