30秒学会 Dart 片段 · 2019年5月12日

30秒学会 Dart 片段 – capitalize

Capitalizes the first letter of a string.

Use String.toUpperCase() to capitalize first letter and String.toLowerCase() to convert the rest of the string to lowercase, if necessary.
Omit the optional parameter, lowerRest, to keep the rest of the string intact, or set it to true to convert to lowercase.

代码实现

String capitalize(String str, {bool lowerRest = false}) {
  return str[0].toUpperCase() +
      (lowerRest ? str.substring(1).toLowerCase() : str.substring(1));
}

使用样例

capitalize('fooBar'); // 'FooBar'
capitalize('fooBar', lowerRest: true); // 'Foobar'