字串是一系列字元。Dart將字串表示為Unicode UTF-16代碼單元序列。Unicode是一種格式,用於為每個字母,數字和符號定義唯一的數值。
由於Dart字串是UTF-16代碼單元序列,因此字串中的32位Unicode值使用特殊語法表示。符文是表示Unicode代碼點的整數。
dart:core
庫中的String類提供了訪問符文的機制。可以通過三種方式訪問字串代碼單元/符文 -
- 使用
String.codeUnitAt()
函數 - 使用
String.codeUnits
屬性 - 使用
String.runes
屬性
String.codeUnitAt()函數
可以通過索引訪問字串中的代碼單元。返回給定索引處的16位UTF-16代碼單元。
語法
String.codeUnitAt(int index);
示例
import 'dart:core';
void main(){
f1();
}
f1() {
String x = 'Runes';
print(x.codeUnitAt(0));
}
執行上面示例代碼,得到以下結果 -
82
String.codeUnits屬性
此屬性返回指定字串的UTF-16代碼單元的不可修改列表。
語法
String. codeUnits;
示例
import 'dart:core';
void main(){
f1();
}
f1() {
String x = 'xuhuhu.com';
print(x.codeUnits);
}
執行上面示例代碼,得到以下結果 -
[89, 105, 105, 98, 97, 105, 46, 99, 111, 109]
String.runes屬性
此屬性返回此字串的可迭代Unicode代碼點,Runes可迭代擴展。
語法
String.runes
示例
void main(){
"Maxsu".runes.forEach((int rune) {
var character=new String.fromCharCode(rune);
print(character);
});
}
執行上面示例代碼,得到以下結果 -
M
a
x
s
u
Unicode代碼點通常表示為\uXXXX
,其中XXXX
是4
位十六進制值。要指定多於或少於4個十六進制數字,請將值放在大括弧中。可以在dart:core
庫中使用Runes類的構造函數。
示例
main() {
Runes input = new Runes(' \u{1f605} ');
print(new String.fromCharCodes(input));
}
上一篇:
Dart符號(Symbol)
下一篇:
Dart枚舉