Capitalizing a string

Dart:
Capitalizing a string

How to:

Using Dart’s Built-in Methods

Dart provides simple, straightforward methods for string manipulation. To capitalize a word or a sentence, you would typically take the first character, convert it to uppercase, and then concatenate it with the rest of the string. Here is how you could implement it:

String capitalize(String text) {
  if (text.isEmpty) return text;
  return text[0].toUpperCase() + text.substring(1).toLowerCase();
}

void main() {
  var example = "hello world";
  print(capitalize(example)); // Output: Hello world
}

Capitalizing Each Word

To capitalize the first letter of each word in a string, you could split the string into words, capitalize each one, and then join them back together:

String capitalizeWords(String text) {
  return text.split(' ').map(capitalize).join(' ');
}

void main() {
  var example = "hello dart enthusiasts";
  print(capitalizeWords(example)); // Output: Hello Dart Enthusiasts
}

Using Third-party Libraries

While Dart’s standard library covers basic needs, certain tasks might be more conveniently accomplished using third-party packages. A popular choice for extended string manipulation capabilities, including capitalization, is the recase package. After adding it to your project’s pubspec.yaml, you can easily capitalize strings among other functionalities:

import 'package:recase/recase.dart';

void main() {
  var example = "hello world";
  var rc = ReCase(example);

  print(rc.titleCase); // Output: Hello World
}

Using recase, you can capitalize individual words, entire sentences, or even follow other casing conventions without manually handling the string transformations.