1

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

1
  • This has nothing to do with Flutter, but everything with Dart.
    – Peter B
    Commented Aug 9, 2023 at 9:33

2 Answers 2

2

You can try my Extension code to get the needed output:

Extension code:

extension StringExtension on String {
  String removeExtraSpaces() {
    return replaceAll(RegExp(r'\s+'), ' ').trim();
  }

  String capitalizeWord() {
    return split(' ').map((word) {
      if (word.isEmpty) return '';
      return '${word[0].toUpperCase()}${word.substring(1).toLowerCase()}';
    }).join(' ');
  }
}

Use like this:

 String str = '  i   love  flutter   ';
 print("${str.removeExtraSpaces().capitalizeWord()}");

Output: I Love Flutter

1

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());
}
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.