Q&D: String and Iterable in Dart
By default, String s in Dart can't be used as Iterable , they must be converted to a List<int> or another kind of Iterable class. To do that, one must import the dart:convert module and start playing with the converters. A pure ASCII string can be converted using ascii.encode(str) , where str is the String to convert to List<int> . import 'dart:convert' ; void main () { final str = "hello world"…
In Dart, a String cannot be used directly as an Iterable. To convert a String into a List or another Iterable class, one must import the dart:convert module and utilize its converters. For a pure ASCII string, the ascii.encode(str) method can be employed, where str is the String to be converted to List<int>. The following Dart code demonstrates this:
import 'dart:convert';
void main() {
final str = 'hello world';
for (var c in ascii.encode(str)) {
print('$c (${String.fromCharCode(c)})');
}
}
When run, this code outputs each character of the string along with its ASCII value: 104 (h), 101 (e), 108 (l), 108 (l), 111 (o), 32 ( ), 119 (w), 111 (o), 114 (r), 108 (l), and 100 (d).
Similarly, an utf8 String can also be converted into an Iterable. Consider the following Dart code:
import 'dart:convert';
void main() {
final str = '波動拳: ↓↙←Ⓑ';
for (var c in utf8.encode(str)) {
print('$c (${String.fromCharCode(c)})');
}
}
Upon execution, this code will display the character along with its UTF-8 encoded value. For instance, the first character '波' is represented as 230 (æ), 179 (³), and 162 (¢). The output appears normal because an utf8 character is encoded in 8, 16, or 32 bits, but the encoder outputs the characters only in 8 bits. This results in an utf8 character being split across multiple bytes.
To avoid this, one can use the String.split() method to generate a List and iterate over it. The following Dart code accomplishes this:
void main() {
final str = '波動拳: ↓↙←Ⓑ';
for (var c in str.split('')) {
print('$c : ${utf8.encode(c)}');
}
}
The output of this code is as follows: '波 : [230, 179, 162]', '動 : [229, 139, 149]', '拳 : [230, 139, 179]', ':' : [58], ' ' : [32], '↓ : [226, 134, 147]', '↙ : [226, 134, 153]', '← : [226, 134, 144]', 'Ⓑ : [226, 146, 183]'. Each Unicode character is represented by its corresponding integers.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.