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

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


当前回答

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

其他回答

最简单的答案是:

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

这里username是字符串。

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

检查空字符串大小写,同样使用短符号:

  String capitalizeFirstLetter(String s) =>
  (s?.isNotEmpty ?? false) ? '${s[0].toUpperCase()}${s.substring(1)}' : s;

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

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

其他答案中的子字符串解析不考虑地区差异。 intl/intl中的toBeginningOfSentenceCase()函数。dart包处理土耳其语和阿塞拜疆语中的基本句型和虚线“i”。

import 'package:intl/intl.dart' show toBeginningOfSentenceCase;

print(toBeginningOfSentenceCase('this is a string'));