Home > database >  how to process string data like this 'Stephen Hawking Einstein' be like this 'SH'
how to process string data like this 'Stephen Hawking Einstein' be like this 'SH'

Time:10-28

how to process string data like this 'Stephen Hawking Einstein' be like this 'SH'.

Text('Stephen Hawking Einstein')

CodePudding user response:

Create an extension somewhere in your application.

extension MemberStringAbbreviation on String {
  String abbreviation() {
    var stringData = this;
    if (stringData.isEmpty) return '';

    var splitStringSpace = stringData.split(' ');

    //Rule for a string of n letters.
    if (splitStringSpace.length == 1) {
      var firstWord = splitStringSpace[0];

      //Rule to extract the first letter of the string.
      if (firstWord.length == 1) {
        return firstWord.toUpperCase();
      }

      //Rule for extracting the first two letters of a string.
      if (firstWord.length > 1) {
        return firstWord.substring(0, 2).toUpperCase();
      }
      return '';
    }

    //Rule for two or more n-letter words.
    if (splitStringSpace.length >= 2) {
      var firstWord = splitStringSpace[0].toUpperCase();
      var secondWord = splitStringSpace[1].toUpperCase();

      return '${firstWord[0]}${secondWord[0]}';
    }

    return '';
  }
}

Import and use the extension

Text('Stephen Hawking Einstein'.abbreviation());
Text('Stephen Hawking'.abbreviation());
Text('Stephen'.abbreviation());
Text('St'.abbreviation());
Text('S'.abbreviation());
Text('Stephen H'.abbreviation());
Text('S H'.abbreviation());

CodePudding user response:

You can split the string by spaces. Like this:

String name = 'Stephen Hawking Einstein';
String abbreviatedName = '';

for(int i = 0; i < name.split(' ').length; i  )
{
    abbreviatedName  = name.split(' ')[i][0];
}

In Text widget:

Text(
    abbreviatedName,
)
  • Related