如何在 Dart 中逐个字符地迭代字符串?

发布于 2025-01-05 20:38:25 字数 51 浏览 2 评论 0原文

我没有看到 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

月朦胧 2025-01-12 20:38:25

另一种实现(使用基本多语言平面之外的字符):

"A string".runes.forEach((int rune) {
  var character=new String.fromCharCode(rune);
  print(character);
});

An alternative implementation (working with characters outside the basic multilingual plane):

"A string".runes.forEach((int rune) {
  var character=new String.fromCharCode(rune);
  print(character);
});
黯然 2025-01-12 20:38:25

您还可以使用 split 方法 来生成字符的列表

input.split('').forEach((ch) => print(ch));

You could also use the split method to generate a List of characters.

input.split('').forEach((ch) => print(ch));
貪欢 2025-01-12 20:38:25

不幸的是 strings 当前不可迭代,因此您必须使用像这样的 for 循环

for(int i=0; i<s.length; i++) {
  var char = s[i];
}

请注意Dart 没有字符类,因此 string[index] 将返回另一个字符串。

Unfortunately strings are currently not iterable so you would have to use a for loop like this

for(int i=0; i<s.length; i++) {
  var char = s[i];
}

Note that Dart does not have a character class so string[index] will return another string.

归属感 2025-01-12 20:38:25

使用 Flutter 字符类

import 'package:flutter/material.dart';
var characters = aString.characters;

With Flutter Characters Class

import 'package:flutter/material.dart';
var characters = aString.characters;
清秋悲枫 2025-01-12 20:38:25

正确迭代 String 的扩展:

extension on String {

  /// To iterate a [String]: `"Hello".iterable()`
  Iterable<String> iterable() sync* {
    for (var i = 0; i < length; i++) {
      yield this[i];
    }}}

像这样使用它:

expect("Hello".iterable(), ["H", "e", "l", "l", "o"]);

但是,如果添加 字符package

import "package:characters/characters.dart"; 

然后您可以使用扩展来使用简单字符或 Unicode 字素正确迭代 String

extension on String {

  /// To iterate a [String]: `"Hello".iterable()`
  /// This will use simple characters. If you want to use Unicode Grapheme
  /// from the [Characters] library, passa [chars] true.
  Iterable<String> iterable({bool unicode = false}) sync* {
    if (unicode) {
      var iterator = Characters(this).iterator;
      while (iterator.moveNext()) {
        yield iterator.current;
      }
    } else
      for (var i = 0; i < length; i++) {
        yield this[i];
      }
  }
}

为了证明它有效:

  test('String.iterable()', () {
expect("Hello".iterable(), ["H", "e", "l", "l", "o"]);
expect("Hello".iterable(unicode: true), ["H", "e", "l", "l", "o"]);

expect("

Extension to properly iterate a String:

extension on String {

  /// To iterate a [String]: `"Hello".iterable()`
  Iterable<String> iterable() sync* {
    for (var i = 0; i < length; i++) {
      yield this[i];
    }}}

Use it like this:

expect("Hello".iterable(), ["H", "e", "l", "l", "o"]);

However, if you add the Characters package:

import "package:characters/characters.dart"; 

Then you can have an extension to properly iterate a String using both simple characters or Unicode graphemes:

extension on String {

  /// To iterate a [String]: `"Hello".iterable()`
  /// This will use simple characters. If you want to use Unicode Grapheme
  /// from the [Characters] library, passa [chars] true.
  Iterable<String> iterable({bool unicode = false}) sync* {
    if (unicode) {
      var iterator = Characters(this).iterator;
      while (iterator.moveNext()) {
        yield iterator.current;
      }
    } else
      for (var i = 0; i < length; i++) {
        yield this[i];
      }
  }
}

To prove it works:

  test('String.iterable()', () {
    expect("Hello".iterable(), ["H", "e", "l", "l", "o"]);
    expect("Hello".iterable(unicode: true), ["H", "e", "l", "l", "o"]);

    expect("????".iterable().length, 2);
    expect("????".iterable().map((s) => s.codeUnitAt(0)), [55357, 56842]);

    expect("????".iterable(unicode: true).length, 1);
    expect("????".iterable(unicode: true), ["????"]);
  });
伏妖词 2025-01-12 20:38:25

extension on String {
  //toArray1 method
  List toArray1() {
    List items = [];
    for (var i = 0; i < this.length; i++) {
      items.add(this[i]);
    }
    return items;
  }

  //toArray2 method
  List toArray2() {
    List items = [];
    this.split("").forEach((item) => items.add(item));
    return items;
  }
}

main(List<String> args) {
  var str = "hello world hello world hello world hello world hello world";
  final stopwatch1 = Stopwatch()..start();
  print(str.toArray1());
  print('str.toArray1() executed in ${stopwatch1.elapsed}');

  final stopwatch2 = Stopwatch()..start();
  print(str.toArray2());
  print('str.toArray2() executed in ${stopwatch2.elapsed}');


}

上面是使用 for 循环和 foreach 的示例,但我测试的结果是,foreach 的工作速度比 for 循环快得多。抱歉,如果我错了,但这是我的测试。


extension on String {
  //toArray1 method
  List toArray1() {
    List items = [];
    for (var i = 0; i < this.length; i++) {
      items.add(this[i]);
    }
    return items;
  }

  //toArray2 method
  List toArray2() {
    List items = [];
    this.split("").forEach((item) => items.add(item));
    return items;
  }
}

main(List<String> args) {
  var str = "hello world hello world hello world hello world hello world";
  final stopwatch1 = Stopwatch()..start();
  print(str.toArray1());
  print('str.toArray1() executed in ${stopwatch1.elapsed}');

  final stopwatch2 = Stopwatch()..start();
  print(str.toArray2());
  print('str.toArray2() executed in ${stopwatch2.elapsed}');


}

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.

请远离我 2025-01-12 20:38:25

这也可以是解决方案:如果您觉得容易,请使用它

String text = "findlastcharacter";
var array = text.split('');
array.forEach((element) { 
 print(element); // iterating char by char 
});
String lastchar = array[array.length - 1];
print('last char is = $lastchar'); // last char is = r

谢谢

This also can be the solution : use it if you find it easy

String text = "findlastcharacter";
var array = text.split('');
array.forEach((element) { 
 print(element); // iterating char by char 
});
String lastchar = array[array.length - 1];
print('last char is = $lastchar'); // last char is = r

Thanks

俯瞰星空 2025-01-12 20:38:25
import 'package:characters/characters.dart';  
      
String myString = "Hi";
for (var char in myString.characters) {
   print(char);
}
H
i

如果您从字符开始,需要注意的一件事是它们将被转换为字符串。

Characters myCharacters = "Hi.characters".characters;      
for (var char in myCharacters) {
        assert(char is String);
        print(char);
}
H
i
import 'package:characters/characters.dart';  
      
String myString = "Hi";
for (var char in myString.characters) {
   print(char);
}
H
i

One thing to be aware of if you are starting with Characters is that they will be converted to String.

Characters myCharacters = "Hi.characters".characters;      
for (var char in myCharacters) {
        assert(char is String);
        print(char);
}
H
i
情深缘浅 2025-01-12 20:38:25

只是一个快速概述,您应该使用字符包:


import "package:characters/characters.dart";

main() {
print("

Just a quick overview, you should defenetly use the characters package:


import "package:characters/characters.dart";

main() {
  print("????‍♂️".characters);
  print("????‍♂️".characters.length);
  print("????‍♂️".runes);
  print("????‍♂️".runes.length);
  print("????‍♂️".codeUnits);
  print("????‍♂️".codeUnits.length);
}

will output

????‍♂️
1
(129492, 8205, 9794, 65039)
4
[55358, 56788, 8205, 9794, 65039]
5
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文