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

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


当前回答

你可以使用字符串库的capitalize()方法,它现在在0.1.2版本中可用, 并确保在pubspec.yaml中添加依赖:

dependencies:
  strings: ^0.1.2

并将其导入dart文件:

import 'package:strings/strings.dart';

现在你可以使用这个方法了,它的原型如下:

String capitalize(String string)

例子:

print(capitalize("mark")); => Mark 

其他回答

把这个拷贝到某个地方:

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'

下面是我使用dart String方法的答案。

String name = "big";
String getFirstLetter = name.substring(0, 1);    
String capitalizedFirstLetter =
      name.replaceRange(0, 1, getFirstLetter.toUpperCase());  
print(capitalizedFirstLetter);

有一个包含该函数的utils包。它有一些更好的方法来操作字符串。

安装方法:

dependencies:
  basic_utils: ^1.2.0

用法:

String capitalized = StringUtils.capitalize("helloworld");

Github:

https://github.com/Ephenodrom/Dart-Basic-Utils

使用字符而不是代码单位

正如文章中所描述的,正确的Dart字符串操作(参见场景4),无论何时处理用户输入,都应该使用字符而不是索引。

// import 'package:characters/characters.dart';

final sentence = 'e\u0301tienne is eating.'; // étienne is eating.
final firstCharacter = sentence.characters.first.toUpperCase();
final otherCharacters = sentence.characters.skip(1);
final capitalized = '$firstCharacter$otherCharacters';
print(capitalized); // Étienne is eating.

在这个特殊的例子中,即使您使用索引,它仍然可以工作,但养成使用字符的习惯仍然是一个好主意。

字符包随Flutter一起提供,因此不需要导入。在纯Dart项目中,您需要添加导入,但不需要向pubspec.yaml添加任何内容。

如果您使用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