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

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

其他回答

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 capitalize(String input) {
  if (input == null) {
    throw new ArgumentError("string: $input");
  }
  if (input.length == 0) {
    return input;
  }
  return input[0].toUpperCase() + input.substring(1);
}

从dart 2.6版本开始,dart支持扩展:

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

所以你可以像这样调用你的扩展:

import "string_extension.dart";

var someCapitalizedString = "someString".capitalize();
extension StringExtension on String {
  String capitalize() {
    return this
        .toLowerCase()
        .split(" ")
        .map((word) => word[0].toUpperCase() + word.substring(1, word.length))
        .join(" ");
  }
}

对于感兴趣的人,这应该适用于任何字符串

非常晚,但是我用,


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