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

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


当前回答

使用字符而不是代码单位

正如文章中所描述的,正确的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添加任何内容。

其他回答

简单,没有任何扩展:

title = "some title without first capital"

title.replaceRange(0, 1, title[0].toUpperCase())

// Result: "Some title without first capital"

把这个拷贝到某个地方:

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'
String fullNameString =
    txtControllerName.value.text.trim().substring(0, 1).toUpperCase() +
        txtControllerName.value.text.trim().substring(1).toLowerCase();

这个代码适用于我。

String name = 'amina';    

print(${name[0].toUpperCase()}${name.substring(1).toLowerCase()});

我使用了不同的实现:

创建一个类:

import 'package:flutter/services.dart';

class FirstLetterTextFormatter extends TextInputFormatter {
  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {
    return TextEditingValue(
      //text: newValue.text?.toUpperCase(),
      text: normaliseName(newValue.text),
      selection: newValue.selection,
    );
  }

  /// Fixes name cases; Capitalizes Each Word.
  String normaliseName(String name) {
    final stringBuffer = StringBuffer();

    var capitalizeNext = true;
    for (final letter in name.toLowerCase().codeUnits) {
      // UTF-16: A-Z => 65-90, a-z => 97-122.
      if (capitalizeNext && letter >= 97 && letter <= 122) {
        stringBuffer.writeCharCode(letter - 32);
        capitalizeNext = false;
      } else {
        // UTF-16: 32 == space, 46 == period
        if (letter == 32 || letter == 46) capitalizeNext = true;
        stringBuffer.writeCharCode(letter);
      }
    }

    return stringBuffer.toString();
  }
}

然后你导入类到任何页面,你需要例如在TextField的inputFormatters属性,只是调用上面的小部件:


TextField(
inputformatters: [FirstLetterTextFormatter()]),
),