Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to capitalized all words first letter to capital in flutter

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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());
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading