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

例如,“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"

其他回答

还应该检查字符串是空还是空。

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);
}

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

安装方法:

dependencies:
  basic_utils: ^1.2.0

用法:

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

Github:

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

在范围内检查。 成语作为Dart >2.16.1

作为一个函数

String capitalize(String str) =>
    str.isNotEmpty
        ? str[0].toUpperCase() + str.substring(1)
        : str;

作为延伸

extension StringExtension on String {
    String get capitalize => 
        isNotEmpty 
            ? this[0].toUpperCase() + substring(1) 
            : this;
}

尝试此代码大写的任何字符串的第一个字母在飞镖扑动

Example: hiii how are you

    Code:
     String str="hiii how are you";
     Text( '${str[0].toUpperCase()}${str.substring(1)}',)`

Output: Hiii how are you
capitalize("your text");

简单地将文本包装为大写部件,它使您的文本(您的文本)为(您的文本) .. 祝你今天愉快