Dart program to capitalize the first character of a string

Dart program to capitalize the first character of a string :

Dart doesn’t provide any inbuilt method to capitalize the first string character. We can either write our own utility function or we can use the intl package. In this blog post, I will show you two different ways to capitalize the first letter of a dart string.

Method 1 : Using toUpperCase() and substring() :

We can get the first character of the string, capitalize it and concatenate it with the rest of the string. toUpperCase method is used to convert one character to uppercase. To get the first character, we can use 0th index as : string[0].

substring() method takes the index from which we need the substring to start. In our case, we will provide 1 i.e. the second character of the string.

Below is the complete program :

main(List<string> args) {
  String s = "the quick brown fox jumps over the lazy dog";
  print(s[0].toUpperCase() + s.substring(1));
}

It will print the below output :

The quick brown fox jumps over the lazy dog

Dart capitalize first string character

We can also write the above program like below :

main(List<string> args) {
  String s = "the quick brown fox jumps over the lazy dog";
  print('${s[0].toUpperCase()}${s.substring(1)}');
}

Method 2 : Using toBeginningOfSentenceCase :

Intl package provides localization and internationalization utility functions. One of its method called toBeginningOfSentenceCase can be used to capitalize the first character of a string. If you are using localization on your flutter app, this method is preferred.

It takes one string, converts the first character of that string to uppercase. The conversion is appropriate to the local. Optionally, it also takes the locals information as the second parameter :

String toBeginningOfSentenceCase (String input, [String locale])

The return value is a string.

How to use toBeginningOfSentenceCase :

We need to install intl dependency to our dart project to use this function. Get the latest package from (here)[https://pub.dev/packages/intl#-installing-tab-] and add it to your pubspec.yaml file as dependencies :

dependencies:
  intl: ^x.x.x

Now, install the package using pub get or flutter pub get.

Next, import it in your dart file :

import 'package:intl/intl.dart';

That’s it. Now, you can use this function in your file like below :

import 'package:intl/intl.dart';
main(List<string> arguments) {
  var str = 'the quick brown fox jumps over the lazy dog';
  print(toBeginningOfSentenceCase(str));
}

This program will print :

The quick brown fox jumps over the lazy dog

Dart intl tobeginningofsentencecase

Similar tutorials :