我如何大写字符串的第一个字符,而不改变任何其他字母的情况?
例如,“this is a string”应该给出“this is a string”。
我如何大写字符串的第一个字符,而不改变任何其他字母的情况?
例如,“this is a string”应该给出“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'
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
var original = "this is a string";
var changed = original.substring(0, 1).toUpperCase() + original.substring(1);
还应该检查字符串是空还是空。
String capitalize(String input) {
if (input == null) {
throw new ArgumentError("string: $input");
}
if (input.length == 0) {
return input;
}
return input[0].toUpperCase() + input.substring(1);
}
检查空字符串大小写,同样使用短符号:
String capitalizeFirstLetter(String s) =>
(s?.isNotEmpty ?? false) ? '${s[0].toUpperCase()}${s.substring(1)}' : s;
其他答案中的子字符串解析不考虑地区差异。 intl/intl中的toBeginningOfSentenceCase()函数。dart包处理土耳其语和阿塞拜疆语中的基本句型和虚线“i”。
import 'package:intl/intl.dart' show toBeginningOfSentenceCase;
print(toBeginningOfSentenceCase('this is a string'));
有一个包含该函数的utils包。它有一些更好的方法来操作字符串。
安装方法:
dependencies:
basic_utils: ^1.2.0
用法:
String capitalized = StringUtils.capitalize("helloworld");
Github:
https://github.com/Ephenodrom/Dart-Basic-Utils
一些更流行的其他答案似乎不处理null和”。我更喜欢不必在客户端代码中处理这些情况,我只是想要一个字符串返回无论什么-即使这意味着一个空的情况下为null。
String upperCaseFirst(String s) => (s??'').length<1 ? '' : s[0].toUpperCase() + s.substring(1)
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!');
});
void allWordsCapitilize (String str) {
return str.toLowerCase().split(' ').map((word) {
String leftText = (word.length > 1) ? word.substring(1, word.length) : '';
return word[0].toUpperCase() + leftText;
}).join(' ');
}
allWordsCapitilize('THIS IS A TEST'); //This Is A Test
从dart 2.6版本开始,dart支持扩展:
extension StringExtension on String {
String capitalize() {
return "${this[0].toUpperCase()}${this.substring(1).toLowerCase()}";
}
}
所以你可以像这样调用你的扩展:
import "string_extension.dart";
var someCapitalizedString = "someString".capitalize();
正如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()
你可以用这个包 ReCase 它为您提供了各种大小写转换功能,如:
snake_case dot.case 路径/案例 param-case PascalCase 消息头实例中 标题的情况 camelCase 句子中 CONSTANT_CASE ReCase sample = new ReCase('hello world'); 打印(sample.sentenceCase);//打印'Hello world'
这个代码适用于我。
String name = 'amina';
print(${name[0].toUpperCase()}${name.substring(1).toLowerCase()});
这是使用String类方法splitMapJoin在dart中大写字符串的另一种选择:
var str = 'this is a test';
str = str.splitMapJoin(RegExp(r'\w+'),onMatch: (m)=> '${m.group(0)}'.substring(0,1).toUpperCase() +'${m.group(0)}'.substring(1).toLowerCase() ,onNonMatch: (n)=> ' ');
print(str); // This Is A Test
你可以使用字符串库的capitalize()方法,它现在在0.1.2版本中可用, 并确保在pubspec.yaml中添加依赖:
dependencies:
strings: ^0.1.2
并将其导入dart文件:
import 'package:strings/strings.dart';
现在你可以使用这个方法了,它的原型如下:
String capitalize(String string)
例子:
print(capitalize("mark")); => Mark
String fullNameString =
txtControllerName.value.text.trim().substring(0, 1).toUpperCase() +
txtControllerName.value.text.trim().substring(1).toLowerCase();
奇怪的是,这是不可用的dart开始。下面是一个扩展的大写字符串:
extension StringExtension on String {
String capitalized() {
if (this.isEmpty) return this;
return this[0].toUpperCase() + this.substring(1);
}
}
它首先检查String是否为空,然后将第一个字母大写,并将其余字母相加
用法:
import "path/to/extension/string_extension_file_name.dart";
var capitalizedString = '${'alexander'.capitalized()} ${'hamilton, my name is'.capitalized()} ${'alexander'.capitalized()} ${'hamilton'.capitalized()}');
// Print result: "Alexander Hamilton, my name is Alexander Hamilton"
下面是我使用dart String方法的答案。
String name = "big";
String getFirstLetter = name.substring(0, 1);
String capitalizedFirstLetter =
name.replaceRange(0, 1, getFirstLetter.toUpperCase());
print(capitalizedFirstLetter);
在此分享我的答案
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;
}
你可以使用Text_Tools包,使用简单:
https://pub.dev/packages/text_tools
你的代码应该是这样的:
//This will print 'This is a string
print(TextTools.toUppercaseFirstLetter(text: 'this is a string'));
最简单的答案是:
首先使用下标将字符串的第一个字母大写,然后将字符串的其余部分拼接起来。
这里username是字符串。
用户名[0].toUpperCase() + username.substring(1);
我发现的另一个不健康的解决这个问题的方法是
String myName = "shahzad";
print(myName.substring(0,1).toUpperCase() + myName.substring(1));
这将产生同样的效果,但这是一种相当肮脏的方式。
我已经使用汉娜斯塔克的答案,但它崩溃的应用程序,如果字符串是空的,所以这里是与扩展的解决方案的改进版本:
extension StringExtension on String {
String capitalize() {
if(this.length > 0) {
return "${this[0].toUpperCase()}${this.substring(1)}";
}
return "";
}
}
使用字符而不是代码单位
正如文章中所描述的,正确的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添加任何内容。
我使用了不同的实现:
创建一个类:
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()]),
),
尝试此代码大写的任何字符串的第一个字母在飞镖扑动
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 EasyString on String {
String toCapitalCase() {
var lowerCased = this.toLowerCase();
return lowerCased[0].toUpperCase() + lowerCased.substring(1);
}
}
非常晚,但是我用,
String title = "some string with no first letter caps";
title = title.replaceFirst(title[0], title[0].toUpperCase()); // Some string with no...
extension StringExtension on String {
String capitalize() {
return this
.toLowerCase()
.split(" ")
.map((word) => word[0].toUpperCase() + word.substring(1, word.length))
.join(" ");
}
}
对于感兴趣的人,这应该适用于任何字符串
在范围内检查。 成语作为Dart >2.16.1
作为一个函数
String capitalize(String str) =>
str.isNotEmpty
? str[0].toUpperCase() + str.substring(1)
: str;
作为延伸
extension StringExtension on String {
String get capitalize =>
isNotEmpty
? this[0].toUpperCase() + substring(1)
: this;
}
你可以使用这个函数:
String capitalize(String str) {
return str
.split(' ')
.map((word) => word.substring(0, 1).toUpperCase() + word.substring(1))
.join(' ');
}
下面是代码,如果你想在一个句子中大写每个单词,例如,如果你想大写你客户的fullName的每个部分,你可以简单地在你的模型类中使用以下扩展:
extension StringExtension on String {
String capitalizeFirstLetter() {
return "${this[0].toUpperCase()}${this.substring(1).toLowerCase()}";
}
}
只需使用这个getter
String get formalFullName => fullName.capitalizeFirstLetter().splitMapJoin(RegExp(r' '),
onNonMatch: (str) => str.toString().capitalize());
希望这对大家有所帮助
简单,没有任何扩展:
title = "some title without first capital"
title.replaceRange(0, 1, title[0].toUpperCase())
// Result: "Some title without first capital"
String? toCapitalize(String? input) {
if (input == null || input.isEmpty) return input;
return '${input[0].toUpperCase()}${input.substring(1).toLowerCase()}';
}
或扩展:
extension StringExtension on String {
String? toCapitalize() {
if (this == null || this.isEmpty) return this;
return '${this[0].toUpperCase()}${this.substring(1).toLowerCase()}';
}
}
如果您使用get: ^4.6.5作为flutter的状态管理,则有用于大写的内置扩展
// This will capitalize first letter of every word
print('hello world'.capitalize); // Hello World
// This will capitalize first letter of sentence
print('hello world'.capitalizeFirst); // Hello world
// This will remove all white spaces from sentence
print('hello world'.removeAllWhitespace); // helloworld
// This will convert string to lowerCamelCase
print('This is new world'.camelCase); // thisIsNewWorld
// This will remove all white spaces between the two words and replace it with '-'
print('This is new world'.paramCase); // this-is-new-world