官术网_书友最值得收藏!

  • 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.

主站蜘蛛池模板: 南城县| 桐庐县| 东丽区| 太白县| 乌兰察布市| 泽普县| 太湖县| 苍山县| 叙永县| 东兴市| 隆德县| 遵义县| 郯城县| 克什克腾旗| 宜黄县| 宽甸| 松桃| 喜德县| 剑阁县| 五莲县| 诏安县| 陈巴尔虎旗| 宜宾县| 开平市| 石景山区| 措美县| 海阳市| 安溪县| 韶关市| 沙湾县| 浠水县| 南投县| 霍邱县| 文山县| 桐柏县| 育儿| 蓝山县| 滦南县| 同心县| 离岛区| 濮阳县|