Dart StringBuffer
最后修改日期:2024 年 1 月 28 日
在本文中,我们将展示如何在 Dart 语言中使用 StringBuffer 类高效地连接字符串。
字符串是 UTF-16 码单元的序列。它用于在程序中表示文本。
StringBuffer 是一个类,用于通过连接高效地创建新字符串。它包含用于字符串操作的 write
、writeAll
、writeln
和 clear
成员函数。
Dart StringBuffer 简单示例
以下是一个使用 StringBuffer
的简单 Dart 程序;
main.dart
void main() { var msg = StringBuffer('There are'); msg.write(' three '); msg.writeAll(['hawks', 'in', 'the sky'], " "); String output = msg.toString(); print(output); }
该程序动态构建一个新字符串并将其打印到控制台。
var msg = StringBuffer('There are');
我们创建了一个新的 StringBuffer
实例。我们添加了一些初始文本。
msg.write(' three ');
我们使用 write
插入另一个字符串。
msg.writeAll(['hawks', 'in', 'the sky'], " ");
我们使用 writeAll
插入多个字符串。第一个参数是字符串列表,第二个参数是分隔符。
String output = msg.toString();
最后,我们使用 toString
将字符串缓冲区转换为单个字符串。
$ dart main.dart There are three hawks in the sky
Dart StringBuffer writeln
writeln
方法写入一个新字符串,后跟一个换行符。
main.dart
void main() { var msg = StringBuffer('blue sky\n'); msg.writeln('old owl'); msg.writeln('lonely wolf'); msg.writeln('strict regime'); print(msg.length); print(msg.toString()); }
该示例创建了一个包含多行文本数据的字符串。此外,我们使用 length
打印文本的大小(以字符为单位)。
$ dart main.dart 43 blue sky old owl lonely wolf strict regime
DartStringBuffer isEmpty
我们可以使用 isEmpty
检查字符串缓冲区是否为空。可以使用 clear
删除缓冲区。
main.dart
void main() { var msg = StringBuffer(); check(msg); msg.writeAll(['an', 'old', 'hawk', 'in', 'the', 'sky'], ' '); check(msg); print(msg.toString()); msg.clear(); check(msg); } void check(StringBuffer msg) { if (msg.isEmpty) { print('the buffer is empty'); } else { print('the buffer is not empty'); } }
在程序中,我们使用 StringBuffer
构建一个字符串,并使用 isEmpty
方法检查缓冲区是否为空。
$ dart main.dart the buffer is empty the buffer is not empty an old hawk in the sky the buffer is empty
来源
在本文中,我们介绍了 Dart 中的 StringBuffer 类。
作者
列出 所有 Dart 教程。