Join in Java
函数:Join() 功能:使用选择的分隔符将一个数组合并为一个字符串,这是JavaScript里面提供的方法,在.NET里面也有类似的String.Join方法,可以在指定String数组的每个元素之间串联指定的分隔符 String,从而产生单个串联的字符串,因为大多数遇到的问题就是针对String数组的,所以也勉强够用了。可是Java里面没有这样的方法,这里提供一下解决方案。
public static String join(Collection s, String delimiter) {
StringBuffer buffer = new StringBuffer();
Iterator iter = s.iterator();
while (iter.hasNext()) {
buffer.append(iter.next());
if (iter.hasNext()) {
buffer.append(delimiter);
}
}
return buffer.toString();
}
StringBuffer buffer = new StringBuffer();
Iterator iter = s.iterator();
while (iter.hasNext()) {
buffer.append(iter.next());
if (iter.hasNext()) {
buffer.append(delimiter);
}
}
return buffer.toString();
}
如果把if移出循环的话,效率会有所提高
public static String join(AbstractCollection s, String delimiter) {
StringBuffer buffer = new StringBuffer();
Iterator iter = s.iterator();
if (iter.hasNext()) {
buffer.append(iter.next());
while (iter.hasNext()) {
buffer.append(delimiter);
buffer.append(iter.next());
}
}
return buffer.toString();
}
StringBuffer buffer = new StringBuffer();
Iterator iter = s.iterator();
if (iter.hasNext()) {
buffer.append(iter.next());
while (iter.hasNext()) {
buffer.append(delimiter);
buffer.append(iter.next());
}
}
return buffer.toString();
}
这样看起来更加完善一些
public static String join(AbstractCollection<String> s, String delimiter) {
if (s.isEmpty()) return "";
Iterator<String> iter = s.iterator();
StringBuffer buffer = new StringBuffer(iter.next());
while (iter.hasNext()) buffer.append(delimiter).append(iter.next());
return buffer.toString();
}
if (s.isEmpty()) return "";
Iterator<String> iter = s.iterator();
StringBuffer buffer = new StringBuffer(iter.next());
while (iter.hasNext()) buffer.append(delimiter).append(iter.next());
return buffer.toString();
}