我如何大写字符串的第一个字符,而不改变任何其他字母的情况?
例如,“this is a string”应该给出“this is a string”。
我如何大写字符串的第一个字符,而不改变任何其他字母的情况?
例如,“this is a string”应该给出“this is a string”。
当前回答
从dart 2.6版本开始,dart支持扩展:
extension StringExtension on String {
String capitalize() {
return "${this[0].toUpperCase()}${this.substring(1).toLowerCase()}";
}
}
所以你可以像这样调用你的扩展:
import "string_extension.dart";
var someCapitalizedString = "someString".capitalize();
其他回答
最简单的答案是:
首先使用下标将字符串的第一个字母大写,然后将字符串的其余部分拼接起来。
这里username是字符串。
用户名[0].toUpperCase() + username.substring(1);
你可以使用这个函数:
String capitalize(String str) {
return str
.split(' ')
.map((word) => word.substring(0, 1).toUpperCase() + word.substring(1))
.join(' ');
}
还应该检查字符串是空还是空。
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);
}
尝试此代码大写的任何字符串的第一个字母在飞镖扑动
Example: hiii how are you
Code:
String str="hiii how are you";
Text( '${str[0].toUpperCase()}${str.substring(1)}',)`
Output: Hiii how are you
final helloWorld = 'hello world'.toUpperCase(); 文本(helloWorld);