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

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

其他回答

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

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"

你可以用这个:

extension EasyString on String {
  String toCapitalCase() {
   var lowerCased = this.toLowerCase();
   return lowerCased[0].toUpperCase() + lowerCased.substring(1);
 }
} 

下面是我使用dart String方法的答案。

String name = "big";
String getFirstLetter = name.substring(0, 1);    
String capitalizedFirstLetter =
      name.replaceRange(0, 1, getFirstLetter.toUpperCase());  
print(capitalizedFirstLetter);

非常晚,但是我用,


String title = "some string with no first letter caps";
    
title = title.replaceFirst(title[0], title[0].toUpperCase()); // Some string with no...