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

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


当前回答

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

安装方法:

dependencies:
  basic_utils: ^1.2.0

用法:

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

Github:

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

其他回答

尝试此代码大写的任何字符串的第一个字母在飞镖扑动

Example: hiii how are you

    Code:
     String str="hiii how are you";
     Text( '${str[0].toUpperCase()}${str.substring(1)}',)`

Output: Hiii how are you

把这个拷贝到某个地方:

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'

正如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()

我使用了不同的实现:

创建一个类:

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()]),
),

一些更流行的其他答案似乎不处理null和”。我更喜欢不必在客户端代码中处理这些情况,我只是想要一个字符串返回无论什么-即使这意味着一个空的情况下为null。

String upperCaseFirst(String s) => (s??'').length<1 ? '' : s[0].toUpperCase() + s.substring(1)