- Dart Cookbook
- Ivo Balbaert
- 251字
- 2021-08-05 17:42:49
Concatenating strings
Concatenation can be done in a variety of ways in Dart (refer to the concat_trim_strings
file, and download it from www.packtpub.com/support).
How to do it...
Strings can be concatenated as follows:
String s1 = "Dart", s2 = "Cook", s3 = "Book"; var res = "Dart" " Cook" "Book"; (1) res = "Dart" " Cook" "Book"; (2) res = s1 + " " + s2 + s3; (3) res = "$s1 $s2$s3"; (4) res = [s1, " ", s2, s3].join(); (5) var sb = new StringBuffer(); (6) sb.writeAll([s1, " ", s2, s3]); res = sb.toString(); print(res); // Dart CookBook
How it works...
Adjacent string literals are taken together as one string as shown in line (1), even if they are on different lines as shown in line (2). The +
operator does the same thing (3), as well as string interpolation (4), which is the preferred way. Still there is another way to add join()
to List<String>
as shown in line (5). The most efficient way, especially if you want to apply the +
operator in a for loop, is to work with StringBuffer
as shown in line (6); the concatenation only happens when toString()
is called.
Tip
So if you have to glue a large number of strings together, use StringBuffer
. Avoid concatenation using +
. This will save you memory and will execute the file much faster.
There's more...
The writeAll
method can take an optional separator argument, as in sb.writeAll([s1, " ", s2, s3],'-');
, resulting in Dart- -Cook-Book
.
- GPS/GNSS原理與應用(第3版)
- Hands-On Industrial Internet of Things
- 物聯(lián)網概論(第2版)
- HTML5 Game development with ImpactJS
- 正在爆發(fā)的互聯(lián)網革命
- 電力物聯(lián)網工程技術原理與應用
- 物聯(lián)網之霧:基于霧計算的智能硬件快速反應與安全控制
- 智慧光網絡:關鍵技術、應用實踐和未來演進
- 網管員必讀:網絡管理(第2版)
- 網絡工程實施技術與方案大全
- 計算機網絡技術
- LwIP應用開發(fā)實戰(zhàn)指南:基于STM32
- Professional Scala
- 信息技術安全評估準則:源流、方法與實踐
- INSTANT Social Media Marketing with HootSuite