博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
在Java中使用分隔符(拆分的对立面)连接数组元素的快速简便方法
阅读量:2290 次
发布时间:2019-05-09

本文共 3959 字,大约阅读时间需要 13 分钟。

本文翻译自:

This question already has answers here :
这个问题已经在这里有了答案
(22 answers)
(22个答案)
Closed 4 years ago .
4年前关闭。

See 请参阅

I'm looking for a quick and easy way to do exactly the opposite of split so that it will cause ["a","b","c"] to become "a,b,c" 我正在寻找一种快速简便的方法来完成拆分的相反操作,以便使["a","b","c"]变为"a,b,c"

Iterating through an array requires either adding a condition (if this is not the last element, add the seperator) or using substring to remove the last separator. 遍历数组需要添加条件(如果这不是最后一个元素,请添加分隔符)或使用子字符串删除最后一个分隔符。

I'm sure there is a certified, efficient way to do it (Apache Commons?) 我敢肯定,有一种经过认证的有效方式来做到这一点(Apache Commons?)

How do you prefer doing it in your projects? 您如何在项目中喜欢这样做?


#1楼

参考:


#2楼

All of these other answers include runtime overhead... like using ArrayList.toString().replaceAll(...) which are very wasteful. 所有这些其他答案都包括运行时开销...就像使用ArrayList.toString()。replaceAll(...)一样,这非常浪费。

I will give you the optimal algorithm with zero overhead; 我将为您提供零开销的最优算法; it doesn't look as pretty as the other options, but internally, this is what they are all doing (after piles of other hidden checks, multiple array allocation and other crud). 它看起来不像其他选项那么漂亮,但是在内部,这就是它们的全部功能(在进行其他隐藏检查,多数组分配和其他操作之后)。

Since you already know you are dealing with strings, you can save a bunch of array allocations by performing everything manually. 由于您已经知道要处理字符串,因此可以通过手动执行所有操作来节省大量数组分配。 This isn't pretty, but if you trace the actual method calls made by the other implementations, you'll see it has the least runtime overhead possible. 这不是很漂亮,但是如果您跟踪其他实现所进行的实际方法调用,则会发现它具有最小的运行时开销。

public static String join(String separator, String ... values) {  if (values.length==0)return "";//need at least one element  //all string operations use a new array, so minimize all calls possible  char[] sep = separator.toCharArray();  // determine final size and normalize nulls  int totalSize = (values.length - 1) * sep.length;// separator size  for (int i = 0; i < values.length; i++) {    if (values[i] == null)      values[i] = "";    else      totalSize += values[i].length();  }  //exact size; no bounds checks or resizes  char[] joined = new char[totalSize];  int pos = 0;  //note, we are iterating all the elements except the last one  for (int i = 0, end = values.length-1; i < end; i++) {    System.arraycopy(values[i].toCharArray(), 0,       joined, pos, values[i].length());    pos += values[i].length();    System.arraycopy(sep, 0, joined, pos, sep.length);    pos += sep.length;  }  //now, add the last element;   //this is why we checked values.length == 0 off the hop  System.arraycopy(values[values.length-1].toCharArray(), 0,    joined, pos, values[values.length-1].length());  return new String(joined);}

#3楼

A fast and simple solution without any 3rd party includes. 没有任何第三方的快速简单的解决方案包括。

public static String strJoin(String[] aArr, String sSep) {    StringBuilder sbStr = new StringBuilder();    for (int i = 0, il = aArr.length; i < il; i++) {        if (i > 0)            sbStr.append(sSep);        sbStr.append(aArr[i]);    }    return sbStr.toString();}

#4楼

it's in StringUtils: 它在StringUtils中:


#5楼

"I'm sure there is a certified, efficient way to do it (Apache Commons?)" “我敢肯定有一种经过认证的高效方法(Apache Commons?)”

yes, apparenty it's 是的,显然是

StringUtils.join(array, separator)


#6楼

does indeed have a method which will connect String arrays together with a specified separator. 确实具有方法,该方法将String数组与指定的分隔符连接在一起。

For example: 例如:

String[] s = new String[] {"a", "b", "c"};String joined = StringUtils.join(s, ",");  // "a,b,c"

However, I suspect that, as you mention, there must be some kind of conditional or substring processing in the actual implementation of the above mentioned method. 但是,我怀疑,正如您提到的,在上述方法的实际实现中必须进行某种条件或子字符串处理。

If I were to perform the String joining and didn't have any other reasons to use Commons Lang, I would probably roll my own to reduce the number of dependencies to external libraries. 如果我要执行String联接并且没有其他任何原因要使用Commons Lang,我可能会自己动手减少对外部库的依赖关系。

转载地址:http://xvcnb.baihongyu.com/

你可能感兴趣的文章
6天面试10家,已经拿到offer,Java程序员的面试总结分享
查看>>
渣本的逆袭之路!备战3个月,三面蚂蚁金服成功斩获Offer
查看>>
10月末美团、滴滴、蘑菇街9次面试总结(Java岗)
查看>>
热气腾腾的腾讯后台开发面经(总共五面)
查看>>
深入理解设计模式(设计原则+种设计模式+设计模式PK+设计模式混编)
查看>>
谷歌大佬回国发展,吊打各大厂面试官!吐血总结大厂面试高频点及笔记解析
查看>>
面试复盘:面完字节、美团、阿里等大厂,今年面试到底问什么?
查看>>
从0到1,决战Spring Boot《Spring Boot 2实战之旅》
查看>>
5面终于拿到字节跳动offer!忍不住和大家分享一波
查看>>
拿到阿里、字节offer后。我总结了一线大厂Java面试重难点:Java基础+并发+JVM+算法+框架+分布式+架构设计
查看>>
金九银十已过 成功入职美团,面试回顾及个人总结:算法+框架+Redis+分布式+JVM
查看>>
香!阿里P8手写3份满级“并发编程”笔记,原理→精通→实战
查看>>
五面美团后,我总结出美团面试四大难题:JVM+微服务+MySQL+Redis
查看>>
滴滴Java后台3面题目:网络+内存溢出+各种锁+高性能+消息队列
查看>>
大厂面试果然名不虚传,蚂蚁三面凉经,真的是“太难了”
查看>>
分享一次止于三面的阿里面试之旅,是我不配呀
查看>>
美团工作7年,精华全在这份学习笔记里了,已成功帮助多位朋友拿到5个大厂Offer
查看>>
淘宝架构师又出神作,Java异步编程实战笔记总结,彻底被征服
查看>>
深入OAuth2核心源码,阿里大佬的Spring Security手册惊呆我了
查看>>
普本毕业,阿里五面成功斩下offer,名校出身的我究竟输在哪?
查看>>