我如何大写字符串的第一个字符,而不改变任何其他字母的情况?
例如,“this is a string”应该给出“this is a string”。
我如何大写字符串的第一个字符,而不改变任何其他字母的情况?
例如,“this is a string”应该给出“this is a string”。
当前回答
简单,没有任何扩展:
title = "some title without first capital"
title.replaceRange(0, 1, title[0].toUpperCase())
// Result: "Some title without first capital"
其他回答
使用字符而不是代码单位
正如文章中所描述的,正确的Dart字符串操作(参见场景4),无论何时处理用户输入,都应该使用字符而不是索引。
// 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.
在这个特殊的例子中,即使您使用索引,它仍然可以工作,但养成使用字符的习惯仍然是一个好主意。
字符包随Flutter一起提供,因此不需要导入。在纯Dart项目中,您需要添加导入,但不需要向pubspec.yaml添加任何内容。
还应该检查字符串是空还是空。
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);
}
你可以使用这个函数:
String capitalize(String str) {
return str
.split(' ')
.map((word) => word.substring(0, 1).toUpperCase() + word.substring(1))
.join(' ');
}
String? toCapitalize(String? input) {
if (input == null || input.isEmpty) return input;
return '${input[0].toUpperCase()}${input.substring(1).toLowerCase()}';
}
或扩展:
extension StringExtension on String {
String? toCapitalize() {
if (this == null || this.isEmpty) return this;
return '${this[0].toUpperCase()}${this.substring(1).toLowerCase()}';
}
}
奇怪的是,这是不可用的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"