/// Capitalize the given string [s]
/// Example : hello => Hello, WORLD => World
extension Capitalized on String {
String capitalized() => this.substring(0, 1).toUpperCase() + this.substring(1).toLowerCase();
}
var str = 'this is a test';
str = str.splitMapJoin(RegExp(r'\w+'),onMatch: (m)=> '${m.group(0)}'.substring(0,1).toUpperCase() +'${m.group(0)}'.substring(1).toLowerCase() ,onNonMatch: (n)=> ' ');
print(str); // This Is A Test
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"
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;
}
// import 'package:characters/characters.dart';
final sentence = 'e\u0301tienne is eating.'; // étienne is eating.
final firstCharacter = sentence.characters.first.toUpperCase();
final otherCharacters = sentence.characters.skip(1);
final capitalized = '$firstCharacter$otherCharacters';
print(capitalized); // Étienne is eating.