我如何大写字符串的第一个字符,而不改变任何其他字母的情况?
例如,“this is a string”应该给出“this is a string”。
我如何大写字符串的第一个字符,而不改变任何其他字母的情况?
例如,“this is a string”应该给出“this is a string”。
当前回答
你可以使用字符串库的capitalize()方法,它现在在0.1.2版本中可用, 并确保在pubspec.yaml中添加依赖:
dependencies:
strings: ^0.1.2
并将其导入dart文件:
import 'package:strings/strings.dart';
现在你可以使用这个方法了,它的原型如下:
String capitalize(String string)
例子:
print(capitalize("mark")); => Mark
其他回答
检查空字符串大小写,同样使用短符号:
String capitalizeFirstLetter(String s) =>
(s?.isNotEmpty ?? false) ? '${s[0].toUpperCase()}${s.substring(1)}' : s;
一些更流行的其他答案似乎不处理null和”。我更喜欢不必在客户端代码中处理这些情况,我只是想要一个字符串返回无论什么-即使这意味着一个空的情况下为null。
String upperCaseFirst(String s) => (s??'').length<1 ? '' : s[0].toUpperCase() + s.substring(1)
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
在此分享我的答案
void main() {
var data = allWordsCapitilize(" hi ram good day");
print(data);
}
String allWordsCapitilize(String value) {
var result = value[0].toUpperCase();
for (int i = 1; i < value.length; i++) {
if (value[i - 1] == " ") {
result = result + value[i].toUpperCase();
} else {
result = result + value[i];
}
}
return result;
}
如果您使用get: ^4.6.5作为flutter的状态管理,则有用于大写的内置扩展
// This will capitalize first letter of every word
print('hello world'.capitalize); // Hello World
// This will capitalize first letter of sentence
print('hello world'.capitalizeFirst); // Hello world
// This will remove all white spaces from sentence
print('hello world'.removeAllWhitespace); // helloworld
// This will convert string to lowerCamelCase
print('This is new world'.camelCase); // thisIsNewWorld
// This will remove all white spaces between the two words and replace it with '-'
print('This is new world'.paramCase); // this-is-new-world