我如何大写字符串的第一个字符,而不改变任何其他字母的情况?

例如,“this is a string”应该给出“this is a string”。


当前回答

void main() {
  print(capitalize("this is a string"));
  // displays "This is a string"
}

String capitalize(String s) => s[0].toUpperCase() + s.substring(1);

查看在DartPad上运行的代码片段:https://dartpad.dartlang.org/c8ffb8995abe259e9643

其他回答

使用字符而不是代码单位

正如文章中所描述的,正确的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添加任何内容。

把这个拷贝到某个地方:

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 main() {
  print(capitalize("this is a string"));
  // displays "This is a string"
}

String capitalize(String s) => s[0].toUpperCase() + s.substring(1);

查看在DartPad上运行的代码片段:https://dartpad.dartlang.org/c8ffb8995abe259e9643

你可以使用Text_Tools包,使用简单:

https://pub.dev/packages/text_tools

你的代码应该是这样的:

//This will print 'This is a string
print(TextTools.toUppercaseFirstLetter(text: 'this is a string'));

你可以使用这个函数:

String capitalize(String str) {
  return str
      .split(' ')
      .map((word) => word.substring(0, 1).toUpperCase() + word.substring(1))
      .join(' ');
}