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

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


当前回答

我已经使用汉娜斯塔克的答案,但它崩溃的应用程序,如果字符串是空的,所以这里是与扩展的解决方案的改进版本:

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

其他回答

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

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

把这个拷贝到某个地方:

extension StringCasingExtension on String {
  String toCapitalized() => length > 0 ?'${this[0].toUpperCase()}${substring(1).toLowerCase()}':'';
  String toTitleCase() => replaceAll(RegExp(' +'), ' ').split(' ').map((str) => str.toCapitalized()).join(' ');
}

用法:

// import StringCasingExtension

final helloWorld = 'hello world'.toCapitalized(); // 'Hello world'
final helloWorld = 'hello world'.toUpperCase(); // 'HELLO WORLD'
final helloWorldCap = 'hello world'.toTitleCase(); // 'Hello World'

final helloWorld = 'hello world'.toUpperCase(); 文本(helloWorld);

最简单的答案是:

首先使用下标将字符串的第一个字母大写,然后将字符串的其余部分拼接起来。

这里username是字符串。

用户名[0].toUpperCase() + username.substring(1);

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