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

例如,“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);
}

在此分享我的答案

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

简单,没有任何扩展:

title = "some title without first capital"

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

// Result: "Some title without first capital"

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

https://pub.dev/packages/text_tools

你的代码应该是这样的:

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

截至2021年3月23日,Flutter 2.0.2

只需使用yourtext.capitalizeFirst