join 方法

String join([
  1. String separator = ""
])
继承

将每个元素转换为 String 并连接这些字符串。

遍历此可迭代的元素,通过调用 Object.toString 将每个元素转换为 String,然后使用 separator 字符串在元素之间交错连接字符串。

示例

final planetsByMass = <double, String>{0.06: 'Mercury', 0.81: 'Venus',
  0.11: 'Mars'};
final joinedNames = planetsByMass.values.join('-'); // Mercury-Venus-Mars

实现

String join([String separator = ""]) {
  int length = this.length;
  if (!separator.isEmpty) {
    if (length == 0) return "";
    String first = "${elementAt(0)}";
    if (length != this.length) {
      throw ConcurrentModificationError(this);
    }
    StringBuffer buffer = StringBuffer(first);
    for (int i = 1; i < length; i++) {
      buffer.write(separator);
      buffer.write(elementAt(i));
      if (length != this.length) {
        throw ConcurrentModificationError(this);
      }
    }
    return buffer.toString();
  } else {
    StringBuffer buffer = StringBuffer();
    for (int i = 0; i < length; i++) {
      buffer.write(elementAt(i));
      if (length != this.length) {
        throw ConcurrentModificationError(this);
      }
    }
    return buffer.toString();
  }
}