我如何大写字符串的第一个字符,而不改变任何其他字母的情况?
例如,“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);
}
其他回答
把这个拷贝到某个地方:
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'
你可以用这个包 ReCase 它为您提供了各种大小写转换功能,如:
snake_case dot.case 路径/案例 param-case PascalCase 消息头实例中 标题的情况 camelCase 句子中 CONSTANT_CASE ReCase sample = new ReCase('hello world'); 打印(sample.sentenceCase);//打印'Hello world'
你可以使用这个函数:
String capitalize(String str) {
return str
.split(' ')
.map((word) => word.substring(0, 1).toUpperCase() + word.substring(1))
.join(' ');
}
我已经使用汉娜斯塔克的答案,但它崩溃的应用程序,如果字符串是空的,所以这里是与扩展的解决方案的改进版本:
extension StringExtension on String {
String capitalize() {
if(this.length > 0) {
return "${this[0].toUpperCase()}${this.substring(1)}";
}
return "";
}
}
capitalize("your text");
简单地将文本包装为大写部件,它使您的文本(您的文本)为(您的文本) .. 祝你今天愉快