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

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


当前回答

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

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

其他回答

String fullNameString =
    txtControllerName.value.text.trim().substring(0, 1).toUpperCase() +
        txtControllerName.value.text.trim().substring(1).toLowerCase();

在此分享我的答案

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;
}
void allWordsCapitilize (String str) {
    return str.toLowerCase().split(' ').map((word) {
      String leftText = (word.length > 1) ? word.substring(1, word.length) : '';
      return word[0].toUpperCase() + leftText;
    }).join(' ');
}
allWordsCapitilize('THIS IS A TEST'); //This Is A Test
String capitalize(String s) => (s != null && s.length > 1)
    ? s[0].toUpperCase() + s.substring(1)
    : s != null ? s.toUpperCase() : null;

它通过了测试:

test('null input', () {
  expect(capitalize(null), null);
});
test('empty input', () {
  expect(capitalize(''), '');
});
test('single char input', () {
  expect(capitalize('a'), 'A');
});
test('crazy input', () {
  expect(capitalize('?a!'), '?a!');
});
test('normal input', () {
  expect(capitalize('take it easy bro!'), 'Take it easy bro!');
});
capitalize("your text");

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