How to convert String index to character index in Dart

[亡魂溺海] 提交于 2021-01-29 06:55:04

问题


If I have an arbitrary String like this:

final family = '\u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467}'; // 👨‍👩‍👧
final myString = 'Let me introduce my $family to you.';

And I know the String index of the character after the family emoji (the space) is 28, how do I find the String index of the first code unit of the family emoji? In other words, how to I find the length in UTF-16 code units of the family emoji?

I've asked a similar question before, but that was before the characters package came out. Is there anything I can do to map the grapheme cluster index to the String index?

The reason I'm asking is that I want to programmatically backspace by grapheme cluster inside a Flutter TextField.


回答1:


It appears that String.characters gives you a list of one grapheme cluster per element. Just remove the stuff a character at a time using a range as described in the docs (https://pub.dev/documentation/characters/latest/characters/CharacterRange-class.html).



来源:https://stackoverflow.com/questions/65445009/how-to-convert-string-index-to-character-index-in-dart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!