capitalizeWords method
Capitalizes the first letter of each word in the string, leaving other characters as they are.
Words are delimited by spaces. If lowerCaseRemaining is set to true, all characters
except the first letter of each word are converted to lowercase.
Parameters:
lowerCaseRemaining: A boolean value. Iftrue, converts the remaining characters of each word to lowercase. Defaults tofalse.
Returns: A new string with the first letter of each word capitalized. Returns the original string if it is empty.
Example:
'hello world'.capitalizeWords(); // Returns 'Hello World'
'mixed CASE words'.capitalizeWords(lowerCaseRemaining: true); // Returns 'Mixed Case Words'
''.capitalizeWords(); // Returns ''
Implementation
String capitalizeWords({bool lowerCaseRemaining = false}) {
if (isEmpty) {
// failed null or empty check
return this;
}
final List<String> originalWords = split(' '); // Keep original words with spaces
// The original code was using words() which effectively removed extra spaces.
final List<String> capitalizedWords = originalWords.map((String word) {
if (word.isNotEmpty) {
return word.capitalize(lowerCaseRemaining: lowerCaseRemaining);
}
return word; // Keep empty strings (for multiple spaces)
}).toList();
return capitalizedWords.join(' ');
}