Skip to content

titleCase

hide-place (abdelhakim sahifa) edited this page Jul 6, 2024 · 1 revision

titleCase

titleCase Function

Description

The titleCase function converts a string to title case, where the first letter of each word is capitalized.

Recent Changes

Empty Input Handling

  • The function now checks if the input string is empty or contains only whitespace. If so, it returns an empty string immediately.

Handling Multiple Spaces

  • The function has been updated to handle multiple spaces between words correctly. It uses split and filters out empty strings to ensure that only valid words are processed.

Simplified Capitalization Logic

  • The capitalization logic has been simplified using Dart's map function. This makes the code more concise and readable.

Mixed Case Input Handling

  • The function now ensures that the rest of each word (after the first letter) is converted to lowercase. This handles mixed case inputs properly.

Usage

Here's an example of how to use the titleCase function:

String title = titleCase("this is an example string");
print(title); // This Is An Example String

Function Explanation

The titleCase function performs the following steps:

  1. Splits the input string into a list of words.
  2. Iterates over each word, capitalizes the first letter, and adds it to a new list.
  3. Joins the capitalized words into a single string with spaces.

Code

String titleCase(String inputString) {
  if(inputString.trim() == ''){
    return '';
  }
  else{
    List<String> wordsList = inputString.trim().split(' ');
    List<String> capitalizedWordsList = [];
    for (var word in wordsList) {
      var capitalizedWord = word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase();
      capitalizedWordsList.add(capitalizedWord);
    }
    String titleCasedString = capitalizedWordsList.join(' ');
    return titleCasedString; 
  }
}

Feel free to contribute by opening issues or pull requests. Let's make string manipulation easier together!

Back to Home