我如何大写字符串的第一个字符,而不改变任何其他字母的情况?
例如,“this is a string”应该给出“this is a string”。
我如何大写字符串的第一个字符,而不改变任何其他字母的情况?
例如,“this is a string”应该给出“this is a string”。
当前回答
还应该检查字符串是空还是空。
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);
}
其他回答
你可以使用Text_Tools包,使用简单:
https://pub.dev/packages/text_tools
你的代码应该是这样的:
//This will print 'This is a string
print(TextTools.toUppercaseFirstLetter(text: 'this is a string'));
有一个包含该函数的utils包。它有一些更好的方法来操作字符串。
安装方法:
dependencies:
basic_utils: ^1.2.0
用法:
String capitalized = StringUtils.capitalize("helloworld");
Github:
https://github.com/Ephenodrom/Dart-Basic-Utils
正如ephendrom之前提到的, 你可以在pubspeck中添加basic_utils包。Yaml和使用它在你的dart文件,像这样:
StringUtils.capitalize("yourString");
对于单个函数来说,这是可以接受的,但在更大的操作链中,这就变得很尴尬了。
正如Dart语言文档中解释的那样:
doMyOtherStuff(doMyStuff(something.doStuff()).doOtherStuff())
该代码的可读性远远低于:
something.doStuff().doMyStuff().doOtherStuff().doMyOtherStuff()
代码也不太容易被发现,因为IDE可以在something.doStuff()之后建议使用doMyStuff(),但不太可能建议在表达式周围使用doMyOtherStuff(…)。
基于这些原因,我认为你应该为String类型添加一个扩展方法(你可以从dart 2.6开始这样做!)
/// Capitalize the given string [s]
/// Example : hello => Hello, WORLD => World
extension Capitalized on String {
String capitalized() => this.substring(0, 1).toUpperCase() + this.substring(1).toLowerCase();
}
并使用点符号调用它:
'yourString'.capitalized()
或者,如果你的值可以为空,用'?在祷文中写道:
myObject.property?.toString()?.capitalized()
void allWordsCapitilize (String str) {
return str.toLowerCase().split(' ').map((word) {
String leftText = (word.length > 1) ? word.substring(1, word.length) : '';
return word[0].toUpperCase() + leftText;
}).join(' ');
}
allWordsCapitilize('THIS IS A TEST'); //This Is A Test
你可以使用这个函数:
String capitalize(String str) {
return str
.split(' ')
.map((word) => word.substring(0, 1).toUpperCase() + word.substring(1))
.join(' ');
}