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

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


当前回答

有一个包含该函数的utils包。它有一些更好的方法来操作字符串。

安装方法:

dependencies:
  basic_utils: ^1.2.0

用法:

String capitalized = StringUtils.capitalize("helloworld");

Github:

https://github.com/Ephenodrom/Dart-Basic-Utils

其他回答

下面是代码,如果你想在一个句子中大写每个单词,例如,如果你想大写你客户的fullName的每个部分,你可以简单地在你的模型类中使用以下扩展:

extension StringExtension on String {
  String capitalizeFirstLetter() {
    return "${this[0].toUpperCase()}${this.substring(1).toLowerCase()}";
  }
}

只需使用这个getter

String get formalFullName =>  fullName.capitalizeFirstLetter().splitMapJoin(RegExp(r' '),
                onNonMatch: (str) => str.toString().capitalize());

希望这对大家有所帮助

我发现的另一个不健康的解决这个问题的方法是

String myName = "shahzad";

print(myName.substring(0,1).toUpperCase() + myName.substring(1));

这将产生同样的效果,但这是一种相当肮脏的方式。

简单,没有任何扩展:

title = "some title without first capital"

title.replaceRange(0, 1, title[0].toUpperCase())

// Result: "Some title without first capital"

有一个包含该函数的utils包。它有一些更好的方法来操作字符串。

安装方法:

dependencies:
  basic_utils: ^1.2.0

用法:

String capitalized = StringUtils.capitalize("helloworld");

Github:

https://github.com/Ephenodrom/Dart-Basic-Utils

其他答案中的子字符串解析不考虑地区差异。 intl/intl中的toBeginningOfSentenceCase()函数。dart包处理土耳其语和阿塞拜疆语中的基本句型和虚线“i”。

import 'package:intl/intl.dart' show toBeginningOfSentenceCase;

print(toBeginningOfSentenceCase('this is a string'));