1

I want to remove white space within a string like extra spaces in between the words. I have tried trim() method. but it only removes the leading and trailing whitespace I want to remove the spaces in between the string and I want to convert the first letter of the each word to capital . example : var name = ' Aneesh devala ' to Aneesh Devala

I have tried this answers but it's not suitable for mine.

Aneesh A
  • 33
  • 5
  • Maybe the answer to your *questions* would be the result of a combination of multiple answers. Perhaps you could use that answer you linked with another question's answer about how to capitalize each word in a string. – Ibrennan208 Jul 30 '22 at 02:02

2 Answers2

2

I hope this code will work for you.

String getCapitalizedName(String name) {
final names = name.split(' ');
String finalName = '';
for (var n in names) {
  n.trim();
  if (n.isNotEmpty) {
    finalName += '${n[0].toUpperCase()}${n.substring(1)} ';
  }
}
return finalName.trim();}
Riyas Tp
  • 68
  • 7
0

you can capitalize each word of a string by define the capitalize() method.

extension StringExtensions on String {
  String capitalize() {
    return '${this[0].toUpperCase()}${substring(1)}';
  }
}

how to use?

String myString = 'capitalized the first letter of every word the string';
String capitalizedString = myString.split(' ').map((word) => word.capitalize()).join(' ');

code example :

class CapitalizeText extends StatefulWidget {
  const CapitalizeText({super.key});

  @override
  State<CapitalizeText> createState() => _CapitalizeTextState();
}

class _CapitalizeTextState extends State<CapitalizeText> {
  @override
  Widget build(BuildContext context) {

    String myString = 'capitalized the first letter of every word the string';
    String capitalizedString =
        myString.split(' ').map((word) => word.capitalize()).join(' ');

    return Scaffold(
      body: Text(
        'Capitalized String - $capitalizedString',
        style: const TextStyle(fontWeight: FontWeight.w200, fontSize: 20),
      ),
    );
  }
}

extension StringExtensions on String {
  String capitalize() {
    return '${this[0].toUpperCase()}${substring(1)}';
  }
}
AKBON
  • 11
  • 4