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

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.

主站蜘蛛池模板: 鲁山县| 怀远县| 寿阳县| 北宁市| 泗洪县| 华池县| 遂宁市| 包头市| 奉贤区| 江陵县| 江川县| 霸州市| 邵武市| 泸州市| 利川市| 桃江县| 广宗县| 黄石市| 津南区| 永新县| 塘沽区| 辉县市| 兰坪| 新宁县| 湖北省| 习水县| 稷山县| 固镇县| 乌拉特前旗| 洪泽县| 进贤县| 丹江口市| 镇江市| 勐海县| 贵德县| 台中县| 墨江| 邵东县| 桦甸市| 高淳县| 仙桃市|