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

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


当前回答

正如ephendrom之前提到的, 你可以在pubspeck中添加basic_utils包。Yaml和使用它在你的dart文件,像这样:

StringUtils.capitalize("yourString");

对于单个函数来说,这是可以接受的,但在更大的操作链中,这就变得很尴尬了。

正如Dart语言文档中解释的那样:

doMyOtherStuff(doMyStuff(something.doStuff()).doOtherStuff())

该代码的可读性远远低于:

something.doStuff().doMyStuff().doOtherStuff().doMyOtherStuff()

代码也不太容易被发现,因为IDE可以在something.doStuff()之后建议使用doMyStuff(),但不太可能建议在表达式周围使用doMyOtherStuff(…)。

基于这些原因,我认为你应该为String类型添加一个扩展方法(你可以从dart 2.6开始这样做!)

/// Capitalize the given string [s]
/// Example : hello => Hello, WORLD => World
extension Capitalized on String {
  String capitalized() => this.substring(0, 1).toUpperCase() + this.substring(1).toLowerCase();
}

并使用点符号调用它:

'yourString'.capitalized()

或者,如果你的值可以为空,用'?在祷文中写道:

myObject.property?.toString()?.capitalized()

其他回答

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

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

String myName = "shahzad";

print(myName.substring(0,1).toUpperCase() + myName.substring(1));

这将产生同样的效果,但这是一种相当肮脏的方式。

最简单的答案是:

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

这里username是字符串。

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

在范围内检查。 成语作为Dart >2.16.1

作为一个函数

String capitalize(String str) =>
    str.isNotEmpty
        ? str[0].toUpperCase() + str.substring(1)
        : str;

作为延伸

extension StringExtension on String {
    String get capitalize => 
        isNotEmpty 
            ? this[0].toUpperCase() + substring(1) 
            : this;
}

如果您使用get: ^4.6.5作为flutter的状态管理,则有用于大写的内置扩展

        // This will capitalize first letter of every word
        print('hello world'.capitalize); // Hello World

        // This will capitalize first letter of sentence
        print('hello world'.capitalizeFirst); // Hello world

        // This will remove all white spaces from sentence
        print('hello world'.removeAllWhitespace); // helloworld

        // This will convert string to lowerCamelCase
        print('This is new world'.camelCase); // thisIsNewWorld

        // This will remove all white spaces between the two words and replace it with '-'
        print('This is new    world'.paramCase); // this-is-new-world