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

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


当前回答

你可以用这个包 ReCase 它为您提供了各种大小写转换功能,如:

snake_case dot.case 路径/案例 param-case PascalCase 消息头实例中 标题的情况 camelCase 句子中 CONSTANT_CASE ReCase sample = new ReCase('hello world'); 打印(sample.sentenceCase);//打印'Hello world'

其他回答

使用字符而不是代码单位

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

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

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

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

在此分享我的答案

void main() {
  var data = allWordsCapitilize(" hi ram good day");
  print(data);
}

String allWordsCapitilize(String value) {
  var result = value[0].toUpperCase();
  for (int i = 1; i < value.length; i++) {
    if (value[i - 1] == " ") {
      result = result + value[i].toUpperCase();
    } else {
      result = result + value[i];
    }
  }
  return result;
}