Reputation: 13582
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".
Upvotes: 269
Views: 232126
Reputation: 657268
Copy this somewhere:
extension StringCasingExtension on String {
String get toCapitalized => length > 0 ?'${this[0].toUpperCase()}${substring(1).toLowerCase()}':'';
String get toTitleCase => replaceAll(RegExp(' +'), ' ').split(' ').map((str) => str.toCapitalized).join(' ');
}
Usage:
// import StringCasingExtension
final helloWorld = 'hello world'.toCapitalized; // 'Hello world'
final helloWorld = 'hello world'.toUpperCase(); // 'HELLO WORLD'
final helloWorldCap = 'hello world'.toTitleCase; // 'Hello World'
Upvotes: 313
Reputation: 1259
Use basics package by Google. The main advantage is that it provides various extensions to the base classes and you can rest assured that they are thoroughly tested.
For example, for the String class there are such extensions as:
See more https://pub.dev/documentation/basics/latest/string_basics/StringBasics.html
Upvotes: 0
Reputation: 3523
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' show toBeginningOfSentenceCase;
print(toBeginningOfSentenceCase('this is a string'));
Result:
This is a string
Upvotes: 204
Reputation: 793
If the Dart version is 2.12 or later, one of the simple and effective solutions to this problem would be,
extension Capitalizing on String {
String get capitalized {
if (isEmpty) return '';
return replaceFirst(this[0], this[0].toUpperCase());
}
}
Writing an extension
on String
class ensures code reusability and clean syntax, you can utilize the extension like this,
String yourString = 'this is a string';
final String capitalizedString = yourString.capitalized; //This is a string
Upvotes: 4
Reputation: 11210
Another way.
import 'package:parser_combinator/parser/any.dart';
import 'package:parser_combinator/parser/choice.dart';
import 'package:parser_combinator/parser/join.dart';
import 'package:parser_combinator/parser/mapped.dart';
import 'package:parser_combinator/parser/rest.dart';
import 'package:parser_combinator/parser/sequence.dart';
import 'package:parser_combinator/parser/value.dart';
import 'package:parser_combinator/parsing.dart';
void main(List<String> args) {
print(capitalize('abc'));
print(capitalize(''));
print(capitalize('xyz'));
print(capitalize('Abc'));
}
String capitalize(String s) {
const p = Choice2(
Join('', Sequence2(Mapped(Any(), _capitalize), Rest())),
Value<String, String>(''),
);
return parseString(p.parse, s);
}
String _capitalize(String s) => s.toUpperCase();
This method is also quite fast.
import 'package:parser_combinator/parser/any.dart';
import 'package:parser_combinator/parser/choice.dart';
import 'package:parser_combinator/parser/join.dart';
import 'package:parser_combinator/parser/mapped.dart';
import 'package:parser_combinator/parser/rest.dart';
import 'package:parser_combinator/parser/sequence.dart';
import 'package:parser_combinator/parser/value.dart';
import 'package:parser_combinator/parsing.dart';
void main(List<String> args) {
const count = 1000000;
final sw = Stopwatch();
sw.start();
for (var i = 0; i < count; i++) {
'abc'.capitalize();
}
sw.stop();
print('Low level: ${sw.elapsedMilliseconds / 1000} sec');
sw.reset();
sw.start();
for (var i = 0; i < count; i++) {
capitalize('abc');
}
sw.stop();
print('High level: ${sw.elapsedMilliseconds / 1000} sec');
}
String capitalize(String s) {
const p = Choice2(
Join('', Sequence2(Mapped(Any(), _capitalize), Rest())),
Value<String, String>(''),
);
return parseString(p.parse, s);
}
String _capitalize(String s) => s.toUpperCase();
extension StringExtension on String {
String capitalize() {
return "${this[0].toUpperCase()}${this.substring(1).toLowerCase()}";
}
}
Output:
Low level: 0.084 sec
High level: 0.304 sec
Upvotes: 0
Reputation: 9
String myString = "hello world";
final capitalizedString = myString.replaceAll(RegExp(' +'), ' ').split(' ').map((capitalizedString) => capitalizedString.substring(0, 1).toUpperCase() +capitalizedString.substring(1)).join(' ');
void main(){
print(capitalizedString);
}
Upvotes: 0
Reputation: 21
you can capitalize each word of a string by define the capitalize() method.
extension StringExtensions on String {
String capitalize() {
return '${this[0].toUpperCase()}${substring(1)}';
}
}
how to use?
String myString = 'capitalized_the_first_letter_of_every_word_the_string';
myString = myString.replaceAll('_', ' ');
String capitalizedString = myString.split(' ').map((word) => word.capitalize()).join(' ');
code example :
class CapitalizeText extends StatefulWidget {
const CapitalizeText({super.key});
@override
State<CapitalizeText> createState() => _CapitalizeTextState();
}
class _CapitalizeTextState extends State<CapitalizeText> {
@override
Widget build(BuildContext context) {
String myString = 'capitalized_the_first_letter_of_every_word_the_string';
myString = myString.replaceAll('_', ' ');
String capitalizedString = myString.split(' ').map((word) => word.capitalize()).join(' ');
return Scaffold(
body: Text(
'Capitalized String - $capitalizedString',
style: const TextStyle(fontWeight: FontWeight.w200, fontSize: 20),
),
);
}
}
extension StringExtensions on String {
String capitalize() {
return '${this[0].toUpperCase()}${substring(1)}';
}
}
Input: capitalized_the_first_letter_of_every_word_the_string
Output: Capitalized The First Letter Of Every Word The String
Upvotes: 1
Reputation: 1174
if you are using it in flutter use as below,
For first letter of string to capitalize :
Text("hello world".toString().capitalizeFirstLetter()),
Convert all letter of string to capital
Text("hello world".toString().toUpperCase()),
Convert all letter of string to small
Text("hello world".toString().toLowerCase()),
Upvotes: -1
Reputation: 1615
Text("hello world".capitalize.toString(), style: TextStyle(
fontSize: 25,
fontWeight: FontWeight.bold,
),
),
Upvotes: 1
Reputation: 1493
Try this code to capitalize the first letter of any String in Dart - Flutter:
Example: hiii how are you
Code:
String str="hiii how are you";
Text( '${str[0].toUpperCase()}${str.substring(1)}',)`
Output: Hiii how are you
Upvotes: -2
Reputation: 91
If you are using get: ^4.6.5 as state management with flutter then there are inbuilt extensions for capitalizing
// 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
Upvotes: 9
Reputation: 800
String? toCapitalize(String? input) {
if (input == null || input.isEmpty) return input;
return '${input[0].toUpperCase()}${input.substring(1).toLowerCase()}';
}
or Extension:
extension StringExtension on String {
String? toCapitalize() {
if (this == null || this.isEmpty) return this;
return '${this[0].toUpperCase()}${this.substring(1).toLowerCase()}';
}
}
Upvotes: 5
Reputation: 179
Simple without any extension:
title = "some title without first capital"
title.replaceRange(0, 1, title[0].toUpperCase())
// Result: "Some title without first capital"
Upvotes: 2
Reputation: 49
capitalize("your text");
simply wrap that text to capitalize widget and it makes your text (your text) to (Your text) .. have a great day
Upvotes: 1
Reputation: 31
Here is the code if you want to capitalize each word in a sentence, for example, if you want to capitalize each part of your customer's fullName, simply you can use the following extension in your model class:
extension StringExtension on String {
String capitalizeFirstLetter() {
return "${this[0].toUpperCase()}${this.substring(1).toLowerCase()}";
}
}
and simply use this getter
String get formalFullName => fullName.capitalizeFirstLetter().splitMapJoin(RegExp(r' '),
onNonMatch: (str) => str.toString().capitalize());
Hope this help someone
Upvotes: 0
Reputation: 20018
You can use this function:
String capitalize(String str) {
return str
.split(' ')
.map((word) => word.substring(0, 1).toUpperCase() + word.substring(1))
.join(' ');
}
Upvotes: 2
Reputation:
var original = "this is a string";
var changed = original.substring(0, 1).toUpperCase() + original.substring(1);
Upvotes: 3
Reputation: 4060
In range checked.
Idiomatic as of Dart >2.16.1
As a function
String capitalize(String str) =>
str.isNotEmpty
? str[0].toUpperCase() + str.substring(1)
: str;
As an extension
extension StringExtension on String {
String get capitalize =>
isNotEmpty
? this[0].toUpperCase() + substring(1)
: this;
}
Upvotes: 3
Reputation: 4052
Since dart version 2.6, dart supports extensions:
extension StringExtension on String {
String capitalize() {
return "${this[0].toUpperCase()}${this.substring(1).toLowerCase()}";
}
}
So you can just call your extension like this:
import "string_extension.dart";
var someCapitalizedString = "someString".capitalize();
Upvotes: 381
Reputation: 76193
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
Upvotes: 82
Reputation: 10
final helloWorld = 'hello world'.toUpperCase(); Text(helloWorld);
Upvotes: -4
Reputation: 1013
Super late, but I use,
String title = "some string with no first letter caps";
title = title.replaceFirst(title[0], title[0].toUpperCase()); // Some string with no...
Upvotes: 24
Reputation: 81
As mentioned before by Ephenodrom, you can add basic_utils package in your pubspeck.yaml and use it in your dart files like this:
StringUtils.capitalize("yourString");
That's acceptable for a single function, but in a larger chain of operations, it becomes awkward.
As explained in Dart language documentation:
doMyOtherStuff(doMyStuff(something.doStuff()).doOtherStuff())
That code is much less readable than:
something.doStuff().doMyStuff().doOtherStuff().doMyOtherStuff()
The code is also much less discoverable because an IDE can suggest doMyStuff()
after something.doStuff()
, but will be unlikely to suggest putting doMyOtherStuff(…)
around the expression.
For these reasons, I think you should add an extension method to String type (you can do it since dart 2.6!) like this:
/// 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();
}
and call it using dot notation:
'yourString'.capitalized()
or, if your value can be null, replacing the dot with a '?.' in the invocation:
myObject.property?.toString()?.capitalized()
Upvotes: 8
Reputation: 510
extension StringExtension on String {
String capitalize() {
return this
.toLowerCase()
.split(" ")
.map((word) => word[0].toUpperCase() + word.substring(1, word.length))
.join(" ");
}
}
For anyone interested, this should work on any string
Upvotes: 3
Reputation: 706
You can use this one:
extension EasyString on String {
String toCapitalCase() {
var lowerCased = this.toLowerCase();
return lowerCased[0].toUpperCase() + lowerCased.substring(1);
}
}
Upvotes: 1
Reputation: 375
I used a different implementation:
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();
}
}
Then you import the class into any page you need eg in a TextField's inputFormatters property, just call the widget above like so:
TextField(
inputformatters: [FirstLetterTextFormatter()]),
),
Upvotes: 0
Reputation: 511706
As described in the article Dart string manipulation done right (see Scenario 4), whenever you are dealing with user input you should use characters
rather than the index.
// 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.
In this particular example it would still work even if you were using the index, but it's still a good idea to get into the habit of using characters
.
The characters package comes with Flutter so there is no need for the import. In a pure Dart project you need to add the import but you don't have to add anything to pubspec.yaml.
Upvotes: 3
Reputation: 1296
I've used Hannah Stark answer, but it crashes the app, if the string is empty, so here is improved version of the solution with the extension:
extension StringExtension on String {
String capitalize() {
if(this.length > 0) {
return "${this[0].toUpperCase()}${this.substring(1)}";
}
return "";
}
}
Upvotes: 1
Reputation: 172
Another unhealthy way I found of solving this issue is to
String myName = "shahzad";
print(myName.substring(0,1).toUpperCase() + myName.substring(1));
this will produce the same effect but is pretty dirty way of doing it.
Upvotes: 1