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

Kasper picture Kasper · Apr 14, 2015 · Viewed 46.7k times · Source

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".

Answer

Günter Zöchbauer picture Günter Zöchbauer · Apr 14, 2015

Copy this somewhere:

extension CapExtension on String {
  String get inCaps => '${this[0].toUpperCase()}${this.substring(1)}';
  String get allInCaps => this.toUpperCase();
  String get capitalizeFirstofEach => this.split(" ").map((str) => str.capitalize).join(" ");
}

Usage:

final helloWorld = 'hello world'.inCaps; // 'Hello world'
final helloWorld = 'hello world'.allInCaps; // 'HELLO WORLD'
final helloWorld = 'hello world'.capitalizeFirstofEach; // 'Hello World'

Old answer:

main() {
  String s = 'this is a string';
  print('${s[0].toUpperCase()}${s.substring(1)}');
}