在 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