Dart/Flutter – How to capitalize first letter of each word in a String

In this post, I will show you an example of how to capitalize first letter of each word in a String. (This kind of String (capitalized first letter of each word) is called “title case”.)

As usual, I will jump directly to the code because there is no specific thing to explain.

void main() {
  String test = 'this is coflutter';

  // Output: This Is Coflutter
  print(convertToTitleCase(test)); 
}

String convertToTitleCase(String text) {
  if (text == null) {
    return null;
  }

  if (text.length <= 1) {
    return text.toUpperCase();
  }

  // Split string into multiple words
  final List<String> words = text.split(' ');

  // Capitalize first letter of each words
  final capitalizedWords = words.map((word) {
    final String firstLetter = word.substring(0, 1).toUpperCase();
    final String remainingLetters = word.substring(1);

    return '$firstLetter$remainingLetters';
  });

  // Join/Merge all words back to one String
  return capitalizedWords.join(' ');
}

Of course we can use Extension methods technique to wrap above method and have more beautiful code.

void main() {
  String test = 'this is coflutter';

  // Test extension, looks more beautiful, right?
  // same output: This Is Coflutter
  print(test.toTitleCase());
}

String convertToTitleCase(String text) {
  if (text == null) {
    return null;
  }

  if (text.length <= 1) {
    return text.toUpperCase();
  }

  // Split string into multiple words
  final List<String> words = text.split(' ');

  // Capitalize first letter of each words
  final capitalizedWords = words.map((word) {
    final String firstLetter = word.substring(0, 1).toUpperCase();
    final String remainingLetters = word.substring(1);

    return '$firstLetter$remainingLetters';
  });

  // Join/Merge all words back to one String
  return capitalizedWords.join(' ');
}

extension CapitalizedStringExtension on String {
  String toTitleCase() {
    return convertToTitleCase(this);
  }
}

If you are looking for mobile/web Software Engineers to build you next projects, please Contact Nextfunc team here!

Tagged : / / / /
0 0 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x