我如何大写字符串的第一个字符,而不改变任何其他字母的情况?
例如,“this is a string”应该给出“this is a string”。
我如何大写字符串的第一个字符,而不改变任何其他字母的情况?
例如,“this is a string”应该给出“this is a string”。
当前回答
最简单的答案是:
首先使用下标将字符串的第一个字母大写,然后将字符串的其余部分拼接起来。
这里username是字符串。
用户名[0].toUpperCase() + username.substring(1);
其他回答
如果您使用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
我使用了不同的实现:
创建一个类:
import 'package:flutter/services.dart';
class FirstLetterTextFormatter extends TextInputFormatter {
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue, TextEditingValue newValue) {
return TextEditingValue(
//text: newValue.text?.toUpperCase(),
text: normaliseName(newValue.text),
selection: newValue.selection,
);
}
/// Fixes name cases; Capitalizes Each Word.
String normaliseName(String name) {
final stringBuffer = StringBuffer();
var capitalizeNext = true;
for (final letter in name.toLowerCase().codeUnits) {
// UTF-16: A-Z => 65-90, a-z => 97-122.
if (capitalizeNext && letter >= 97 && letter <= 122) {
stringBuffer.writeCharCode(letter - 32);
capitalizeNext = false;
} else {
// UTF-16: 32 == space, 46 == period
if (letter == 32 || letter == 46) capitalizeNext = true;
stringBuffer.writeCharCode(letter);
}
}
return stringBuffer.toString();
}
}
然后你导入类到任何页面,你需要例如在TextField的inputFormatters属性,只是调用上面的小部件:
TextField(
inputformatters: [FirstLetterTextFormatter()]),
),
你可以使用字符串库的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 fullNameString =
txtControllerName.value.text.trim().substring(0, 1).toUpperCase() +
txtControllerName.value.text.trim().substring(1).toLowerCase();
在此分享我的答案
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;
}