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;
}
Just a slight modification since you only need the first letters
String getInitials(bank_account_name) {
List<String> names = bank_account_name.split(" ");
String initials = "";
int numWords = 2;
if(numWords < names.length) {
numWords = names.length;
}
for(var i = 0; i < numWords; i++){
initials += '${names[i][0]}';
}
return initials;
}
Edit:
num_words
to print the intials of those many words.bank_account_name
is a 0 letter word, then return an empty stringbank_account_name
contains lesser words than num_words
, print the initials of all the words in bank_account_name
.