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

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


当前回答

你可以使用这个函数:

String capitalize(String str) {
  return str
      .split(' ')
      .map((word) => word.substring(0, 1).toUpperCase() + word.substring(1))
      .join(' ');
}

其他回答

String capitalize(String s) => (s != null && s.length > 1)
    ? s[0].toUpperCase() + s.substring(1)
    : s != null ? s.toUpperCase() : null;

它通过了测试:

test('null input', () {
  expect(capitalize(null), null);
});
test('empty input', () {
  expect(capitalize(''), '');
});
test('single char input', () {
  expect(capitalize('a'), 'A');
});
test('crazy input', () {
  expect(capitalize('?a!'), '?a!');
});
test('normal input', () {
  expect(capitalize('take it easy bro!'), 'Take it easy bro!');
});

我已经使用汉娜斯塔克的答案,但它崩溃的应用程序,如果字符串是空的,所以这里是与扩展的解决方案的改进版本:

extension StringExtension on String {
  String capitalize() {
    if(this.length > 0) {
      return "${this[0].toUpperCase()}${this.substring(1)}";
    }
    return "";
  }
}

简单,没有任何扩展:

title = "some title without first capital"

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

// Result: "Some title without first capital"
void main() {
  print(capitalize("this is a string"));
  // displays "This is a string"
}

String capitalize(String s) => s[0].toUpperCase() + s.substring(1);

查看在DartPad上运行的代码片段:https://dartpad.dartlang.org/c8ffb8995abe259e9643

我使用了不同的实现:

创建一个类:

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