如何在 Dart 中逐个字符地迭代字符串?
我没有看到 Dart 字符串被视为字符列表。我假设我必须使用 for 循环,这会很蹩脚。
I don't see Dart strings treated as lists of characters. I assume I have to use for loops, which would be lame.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
另一种实现(使用基本多语言平面之外的字符):
An alternative implementation (working with characters outside the basic multilingual plane):
您还可以使用 split 方法 来生成字符的
列表
。You could also use the split method to generate a
List
of characters.不幸的是 strings 当前不可迭代,因此您必须使用像这样的 for 循环
请注意Dart 没有字符类,因此 string[index] 将返回另一个字符串。
Unfortunately strings are currently not iterable so you would have to use a for loop like this
Note that Dart does not have a character class so string[index] will return another string.
使用 Flutter 字符类
With Flutter Characters Class
正确迭代
String
的扩展:像这样使用它:
但是,如果添加 字符package:
然后您可以使用扩展来使用简单字符或 Unicode 字素正确迭代
String
:为了证明它有效:
Extension to properly iterate a
String
:Use it like this:
However, if you add the Characters package:
Then you can have an extension to properly iterate a
String
using both simple characters or Unicode graphemes:To prove it works:
上面是使用 for 循环和 foreach 的示例,但我测试的结果是,foreach 的工作速度比 for 循环快得多。抱歉,如果我错了,但这是我的测试。
The above is the example of using for loop and foreach but the result i tested, foreach is working way faster than for loop. Sorry if i was wrong, but it was my tests.
这也可以是解决方案:如果您觉得容易,请使用它
谢谢
This also can be the solution : use it if you find it easy
Thanks
如果您从字符开始,需要注意的一件事是它们将被转换为字符串。
One thing to be aware of if you are starting with Characters is that they will be converted to String.
只是一个快速概述,您应该使用字符包:
Just a quick overview, you should defenetly use the characters package:
will output