Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capitalize the first letter of a string in dart?

People also ask

How do you capitalize first letter?

To use a keyboard shortcut to change between lowercase, UPPERCASE, and Capitalize Each Word, select the text and press SHIFT + F3 until the case you want is applied.

How do you capitalize text in flutter?

As we all know, Flutter is a framework created using the dart programming language. Dart has a method toUpperCase() that is used to capitalize the String text. The basic syntax for that is as below. So we can also use this in our Flutter Text() widget to transform the text to uppercase letters.

How do you capitalize the first and last letter of a string?

Use list slicing and str. upper() to capitalize the first letter of the string. Use str. join() to combine the capitalized first letter with the rest of the characters.

How do I print the first letter of a string in uppercase?

The simplest way to capitalize the first letter of a string in Java is by using the String. substring() method: String str = "hello world!"; // capitalize first letter String output = str.


Since dart version 2.6, dart supports extensions:

extension StringExtension on String {
    String capitalize() {
      return "${this[0].toUpperCase()}${this.substring(1)}";
    }
}

So you can just call your extension like this:

import "string_extension.dart";

var someCapitalizedString = "someString".capitalize();

Copy this somewhere:

extension StringCasingExtension on String {
  String toCapitalized() => length > 0 ?'${this[0].toUpperCase()}${substring(1)}':'';
  String 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'

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

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.