我如何大写字符串的第一个字符,而不改变任何其他字母的情况?
例如,“this is a string”应该给出“this is a string”。
我如何大写字符串的第一个字符,而不改变任何其他字母的情况?
例如,“this is a string”应该给出“this is a string”。
当前回答
非常晚,但是我用,
String title = "some string with no first letter caps";
title = title.replaceFirst(title[0], title[0].toUpperCase()); // Some string with no...
其他回答
把这个拷贝到某个地方:
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'
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
你可以使用Text_Tools包,使用简单:
https://pub.dev/packages/text_tools
你的代码应该是这样的:
//This will print 'This is a string
print(TextTools.toUppercaseFirstLetter(text: 'this is a string'));
奇怪的是,这是不可用的dart开始。下面是一个扩展的大写字符串:
extension StringExtension on String {
String capitalized() {
if (this.isEmpty) return this;
return this[0].toUpperCase() + this.substring(1);
}
}
它首先检查String是否为空,然后将第一个字母大写,并将其余字母相加
用法:
import "path/to/extension/string_extension_file_name.dart";
var capitalizedString = '${'alexander'.capitalized()} ${'hamilton, my name is'.capitalized()} ${'alexander'.capitalized()} ${'hamilton'.capitalized()}');
// Print result: "Alexander Hamilton, my name is Alexander Hamilton"
非常晚,但是我用,
String title = "some string with no first letter caps";
title = title.replaceFirst(title[0], title[0].toUpperCase()); // Some string with no...