在 Dart 中,字串是採用 UTF-16 編碼的序列。
建立字串
var s1 = 'Single quotes work well for string literals.';
var s2 = "Double quotes work just as well.";
var s3 = 'It\'s easy to escape the string delimiter.';
var s4 = "It's even easier to use the other delimiter.";
var s5 = '''
You can create
multi-line strings like this one.
'''
複製程式碼
toString()
所有的物件都具有 toString()
的函式。
var intString = 3.1415.toString();
複製程式碼
在字串中嵌入表示式
你可以直接通過 ${expression}
的格式,在字串中嵌入一個表示式,十分便捷。
CoorChice 喜歡這個特性。
var s = 'string interpolation';
s = 'That deserves all caps.${s.toUpperCase()} is very handy!'
>>>
That deserves all caps.STRING INTERPOLATION is very handy!
複製程式碼
在字串中引用變數
Dart 支援在字串中直接引用變數,通過 $value
的格式。
var num = 1000;
var tips = 'The user num is $num.';
print(tips);
>>>
The user num is 1000.
複製程式碼
建立單行字串
通過 r
字首,可以建立強制單行的字串。
// 不使用 r
var s = 'In a raw string, not even \ngets special treatment.';
>>>
In a raw string, not even
gets special treatment.
// 使用 r
var s = r'In a raw string, not even \ngets special treatment.';
>>>
In a raw string, not even \ngets special treatment.
複製程式碼
字串的比較
在 Dart 中,比較兩個字串可以使用 ==
運算子:
String s1 = 'This is String';
var s2 = 'This is String';
print(s1 == s2);
>>>
true複製程式碼