How to iterate over a String, char by char, in Dart?
26,311
Solution 1
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);
});
Solution 2
You could also use the split method to generate a List
of characters.
input.split('').forEach((ch) => print(ch));
Solution 3
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.
Solution 4
With Flutter Characters Class
import 'package:flutter/material.dart';
var characters = aString.characters;
Solution 5
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.
Comments
-
mcandre almost 2 years
I don't see Dart strings treated as lists of characters. I assume I have to use for loops, which would be lame.
-
CedX over 10 yearsWarning: with some rare foreign languages, the loop does not work as expected.
length
property and[]
operator refers to UTF-16 code units, not characters. Some characters can use 2 UTF-16 code units. -
CedX over 4 yearsStarting with Dart 2.7.0, you can use the package
characters
: pub.dev/packages/characters. -
lordvidex about 4 yearsBonusPoint:: getter codeUnits can also be used in place of runes as in:
"A string".codeUnits.forEach((int c) { var character=new String.fromCharCode(c); print(character); });
-
CedX almost 4 years
String.codeUnits
only deals with UTF-16 code points, whereasString.runes
deals with Unicode code points (UTF-8, UTF-16, UTF-32). A character can be represented by 2 UTF-16 code points (i.e. a surrogate pair), but will be represented by only 1 rune. -
lrn about 2 yearsThe Flutter link is a re-export of
package:characters/characters.dart
which can be used without Flutter too. It is the recommended way to iterate general Unicode text.