-
Notifications
You must be signed in to change notification settings - Fork 0
titleCase
hide-place (abdelhakim sahifa) edited this page Jul 6, 2024
·
1 revision
The titleCase
function converts a string to title case, where the first letter of each word is capitalized.
- The function now checks if the input string is empty or contains only whitespace. If so, it returns an empty string immediately.
- 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.
- The capitalization logic has been simplified using Dart's
map
function. This makes the code more concise and readable.
- The function now ensures that the rest of each word (after the first letter) is converted to lowercase. This handles mixed case inputs properly.
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
The titleCase
function performs the following steps:
- Splits the input string into a list of words.
- Iterates over each word, capitalizes the first letter, and adds it to a new list.
- Joins the capitalized words into a single string with spaces.
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!