如何在flutter dart中从单词中获取第一个字符?

jgwigjjp  于 12个月前  发布在  Flutter
关注(0)|答案(8)|浏览(136)

假设我们有一个名字设置为“Ben Bright”。我想输出给用户“BB”,每个单词的第一个字符。我尝试了split()方法,但我用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;
}

字符串

3bygqnnd

3bygqnnd1#

请允许我给予一个比前面提到的更简短的解决办法:

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()
    : '';

字符串
take(2)部分确保我们最多只能使用两个字母。

编辑(2021年10月7日):

或者,如果我们必须能够处理单词之间的多个空格,我们可以这样做(感谢@StackUnderflow的通知):

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()
    : '';


请注意,与原始解决方案相比,split需要RegExp(' +')

ngynwnxp

ngynwnxp2#

只需稍做修改,因为您只需要第一个字母

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;
}

字符串
编辑:

  • 您可以设置num_words的值以打印这些单词的首字母。“
  • 如果bank_account_name是一个0字母的单词,则返回一个空字符串
  • 如果bank_account_name包含的单词少于num_words,请打印bank_account_name中所有单词的首字母。
rqcrx0a6

rqcrx0a63#

var string = 'William Henry Gates';

var output = getInitials(string: string, limitTo: 1); // W
var output = getInitials(string: string, limitTo: 2); // WH
var output = getInitials(string: string); // WHG
String getInitials({String string, int limitTo}) {
  var buffer = StringBuffer();
  var split = string.split(' ');
  for (var i = 0 ; i < (limitTo ?? split.length); i ++) {
    buffer.write(split[i][0]);
  }

  return buffer.toString();
}
c8ib6hqw

c8ib6hqw4#

一个更通用的解决方案可以在下面找到。它可以处理空字符串,单个单词字符串以及预期字数少于实际字数的情况:

static String getInitials(String string, {int limitTo}) {
  var buffer = StringBuffer();
  var wordList = string.trim().split(' ');
  
  if (string.isEmpty)
    return string;

  // Take first character if string is a single word
  if (wordList.length <= 1)
    return string.characters.first;

  /// Fallback to actual word count if
  /// expected word count is greater
  if (limitTo != null && limitTo > wordList.length) {
    for (var i = 0; i < wordList.length; i++) {
      buffer.write(wordList[i][0]);
    }
    return buffer.toString();
  }

  // Handle all other cases
  for (var i = 0; i < (limitTo ?? wordList.length); i++) {
    buffer.write(wordList[i][0]);
  }
  return buffer.toString();
}

字符串

编辑:

实际上,我在我的项目中没有图像的CircleAvatar s中使用了这个。

atmip9wb

atmip9wb5#

我使用CopsOnRoad解决方案,但我得到了以下错误。
RangeError(index):无效值:仅有效值为0:1
所以我修改了一下

String getInitials(String string, [int limitTo = 2]) {
  if (string == null || string.isEmpty) {
    return '';
  }

  var buffer = StringBuffer();
  var split = string.split(' ');

  //For one word
  if (split.length == 1) {
    return string.substring(0, 1);
  }

  for (var i = 0; i < (limitTo ?? split.length); i++) {
    buffer.write(split[i][0]);
  }

  return buffer.toString();
}

字符串
如果你感兴趣的话,这里有一些测试

void main() {
  group('getInitials', () {
    test('should process one later word name correctly', () {
      final result = getInitials('J');

      expect(result, 'J');
    });

    test('should process one word name correctly', () {
      final result = getInitials('John');

      expect(result, 'J');
    });

    test('should process two word name correctly', () {
      final result = getInitials('John Mamba');

      expect(result, 'JM');
    });

    test('should process more than two word name correctly', () {
      final result = getInitials('John Mamba Kanzu');

      expect(result, 'JM');
    });

    test('should return empty string when name is null', () {
      final result = getInitials(null);

      expect(result, '');
    });

    test('should return empty string when name is empty', () {
      final result = getInitials('');

      expect(result, '');
    });
  });
}

gxwragnw

gxwragnw6#

String getInitials(full_name) {
  List<String> names = full_name.split(" ");
  print("org::: $full_name");
  print("list ::: $names");
  print("Substring  ::: ${names[0].substring(0,1)}");
  String initials = "";
  int numWords = 2;

  numWords = names.length;
  for(var i = 0; i < numWords; i++)
  {
    initials += '${names[i].substring(0,1)}';
    print("the initials are $initials");
  }
  return initials;
}

字符串

sxpgvts3

sxpgvts37#

On Nov,2022使用Regex的工作解决方案:

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

字符串

vdgimpew

vdgimpew8#

getFirstCharFromWord({required String word}){
   String firstChar="";
   word.split(" ").forEach((element) 
    {
    String fc= element.trim().toString();
    fc.isNotEmpty?firstChar+=fc.substring(0,1):"";
    });
return firstChar;
    }

字符串

相关问题