Dart: String

14th December 2020 at 9:09am
Dart

Dart 字符串是一串由 UTF-16 code units 组成的序列。

替换

字符串中可以用 ${expression}。如果 expression 是一个变量,花括号 {} 可以省略。Dart 底层会调用该对象的 toString() 方法:

var s = 'string interpolation';

assert('Dart has $s, which is very handy.' ==
    'Dart has string interpolation, which is very handy.');

比较

字符串的 == 比较的是里面的 code units 是否相同。

字面值

字符串拼接:

var s1 = 'hello ' 'world';
var s2 = 'hello '
    'world';
var s3 = 'hello ' + 'world';

assert(s1 == s2);
assert(s2 == s3);

多行字符串:

var s1 = '''
You can create
multi-line strings like this one.
''';

var s2 = """This is also a
multi-line string.""";

Unicode 操作

使用 Characters 库:

import 'package:characters/characters.dart';
...
var hi = 'Hi 🇩🇰';
print(hi);
print('The end of the string: ${hi.substring(hi.length - 1)}');
print('The last character: ${hi.characters.last}\n');
$ dart bin/main.dart
Hi 🇩🇰
The end of the string: ???
The last character: 🇩🇰