Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get first character from words in flutter dart?

Tags:

dart

Let's say we have a name set to "Ben Bright". I want to output to the user "BB", with the first characters of each word. I tried with the split() method, but I failed to do it with dart.

String getInitials(bank_account_name) {
  List<String> names = bank_account_name.split(" ");
  String initials;
  for (var i = 0; i < names.length; i++) {
    initials = '${names[i]}';
  }
  return initials;
}
like image 779
bensofter Avatar asked Nov 28 '22 19:11

bensofter


1 Answers

Allow me to give a shorter solution than the other mentioned:

void main() {
  print(getInitials('')); //
  print(getInitials('Ben')); // B
  print(getInitials('Ben ')); // B
  print(getInitials('Ben Bright')); // BB
  print(getInitials('Ben Bright Big')); // BB
}

String getInitials(String bank_account_name) => bank_account_name.isNotEmpty
    ? bank_account_name.trim().split(' ').map((l) => l[0]).take(2).join()
    : '';

The take(2) part ensures we only take up to two letters.

EDIT (7th October 2021):

Or if we must be able to handle multiple spaces between the words we can do (thanks @StackUnderflow for notice):

void main() {
  print(getInitials('')); //
  print(getInitials('Ben')); // B
  print(getInitials('Ben ')); // B
  print(getInitials('Ben Bright')); // BB
  print(getInitials('Ben Bright Big')); // BB
  print(getInitials('Ben  Bright    Big')); // BB
}

String getInitials(String bankAccountName) => bankAccountName.isNotEmpty
    ? bankAccountName.trim().split(RegExp(' +')).map((s) => s[0]).take(2).join()
    : '';

Notice that split takes a RegExp(' +') compared to the original solution.

like image 115
julemand101 Avatar answered Dec 23 '22 13:12

julemand101