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

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


当前回答

其他答案中的子字符串解析不考虑地区差异。 intl/intl中的toBeginningOfSentenceCase()函数。dart包处理土耳其语和阿塞拜疆语中的基本句型和虚线“i”。

import 'package:intl/intl.dart' show toBeginningOfSentenceCase;

print(toBeginningOfSentenceCase('this is a string'));

其他回答

把这个拷贝到某个地方:

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 name = 'amina';    

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

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

Example: hiii how are you

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

Output: Hiii how are you

你可以使用Text_Tools包,使用简单:

https://pub.dev/packages/text_tools

你的代码应该是这样的:

//This will print 'This is a string
print(TextTools.toUppercaseFirstLetter(text: 'this is a string'));
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