我如何大写字符串的第一个字符,而不改变任何其他字母的情况?
例如,“this is a string”应该给出“this is a string”。
我如何大写字符串的第一个字符,而不改变任何其他字母的情况?
例如,“this is a string”应该给出“this is a string”。
当前回答
如果您使用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
其他回答
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!');
});
这个代码适用于我。
String name = 'amina';
print(${name[0].toUpperCase()}${name.substring(1).toLowerCase()});
在范围内检查。 成语作为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? 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()}';
}
}
其他答案中的子字符串解析不考虑地区差异。 intl/intl中的toBeginningOfSentenceCase()函数。dart包处理土耳其语和阿塞拜疆语中的基本句型和虚线“i”。
import 'package:intl/intl.dart' show toBeginningOfSentenceCase;
print(toBeginningOfSentenceCase('this is a string'));