How do I capitalize the first character of a string, while not changing the case of any of the other letters?
For example, "this is a string" should give "This is a string".
How do I capitalize the first character of a string, while not changing the case of any of the other letters?
For example, "this is a string" should give "This is a string".
main() {
String s = 'this is a string';
print('${s[0].toUpperCase()}${s.substring(1)}');
}
void main() {
print(capitalize("this is a string"));
// displays "This is a string"
}
String capitalize(String s) => s[0].toUpperCase() + s.substring(1);
See this snippet running on DartPad : https://dartpad.dartlang.org/c8ffb8995abe259e9643
Alternatively you can use the strings package, see capitalize.
Substring parsing in the other answers do not account for locale variances.
The toBeginningOfSentenceCase() function in the intl/intl.dart
package handles basic sentence-casing and the dotted "i" in Turkish and Azeri.
import 'package:intl/intl.dart';
...
String sentence = toBeginningOfSentenceCase('this is a string'); // This is a string
There is a utils package that covers this function. It has some more nice methods for operation on strings.
Install it with :
dependencies:
basic_utils: ^1.2.0
Usage :
String capitalized = StringUtils.capitalize("helloworld");
Github:
https://github.com/Ephenodrom/Dart-Basic-Utils
You should also check if the string is null or empty.
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);
}
To check for null and empty string cases, also using the short notations:
String capitalizeFirstLetter(String s) =>
(s?.isNotEmpty ?? false) ? '${s[0].toUpperCase()}${s.substring(1)}' : s;
String capitalize(String s) => (s != null && s.length > 1)
? s[0].toUpperCase() + s.substring(1)
: s != null ? s.toUpperCase() : null;
It passes tests:
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!');
});
var orig = "this is a string";
var changed = orig.substring(0, 1).toUpperCase + orig.substring(1)
Some of the more popular other answers don't seem to handle null
and ''
. I prefer to not have to deal with those situations in client code, I just want a String
in return no matter what - even if that means an empty one in case of null
.
String upperCaseFirst(String s) => (s??'').length<1 ? '' : s[0].toUpperCase() + s.substring(1)
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