I have created a String Extension with my logic.
I checked previously asked questions in stack overflow, but here I want to implement my code rather than following other logic…
here is my effort
extension StringExtension on String {
String capitalize() {
//to capitalize first letter of string to uppercase
if(trim().isEmpty)
return '';
return "${this[0].toUpperCase()}${this.substring(1)}";
}
String capitalizeEachWord(){
// looking for good code
}
String removeExtraSpaces() {
//to remove all extra spaces between words
if(trim().isEmpty)
return '';
return trim().replaceAll(RegExp(' +'), ' ');
}
}
here is my void main()
String str=' i love flutter ';
print(str.removeExtraSpaces().capitalizeEachWord());
// want output : I Love Flutter
>Solution :
To capitalize every word, iterate through them and capitalize first letter and add the rest of the word. You can do so with split method. The implementation would look something like this:
extension Capitalize on String {
String capitalize() {
if (trim().isNotEmpty) {
final words = removeExtraSpaces()
.split(' ')
.map((e) => e[0].toUpperCase() + (e.length > 1 ? e.substring(1) : ''))
.toList();
return words.join(' ');
}
else return this;
}
String removeExtraSpaces() {
if(trim().isEmpty) return '';
return trim().replaceAll(RegExp(' +'), ' ');
}
}
void main() {
final str = 'i love flutter ';
print(str.capitalize());
}