在 Java 中使用分隔符(与拆分相反)连接数组元素的快速简便方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1978933/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 02:01:11  来源:igfitidea点击:

A quick and easy way to join array elements with a separator (the opposite of split) in Java

javaarraysstring

提问by Eran Medan

See Related .NET question

请参阅相关的 .NET 问题

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"

我正在寻找一种快速简便的方法来做与 split 完全相反的事情,这样它就会 ["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?

你更喜欢在你的项目中如何做?

采纳答案by skiwi

Using Java 8 you can do this in a very clean way:

使用 Java 8,您可以以非常干净的方式执行此操作:

String.join(delimiter, elements);

This works in three ways:

这以三种方式起作用:

1) directly specifying the elements

1) 直接指定元素

String joined1 = String.join(",", "a", "b", "c");

2) using arrays

2) 使用数组

String[] array = new String[] { "a", "b", "c" };
String joined2 = String.join(",", array);

3) using iterables

3)使用迭代

List<String> list = Arrays.asList(array);
String joined3 = String.join(",", list);

回答by Roland Bouman

"I'm sure there is a certified, efficient way to do it (Apache Commons?)"

“我确定有一种经过认证的有效方法(Apache Commons?)”

yes, apparenty it's

是的,显然是

StringUtils.join(array, separator)

http://www.java2s.com/Code/JavaAPI/org.apache.commons.lang/StringUtilsjoinObjectarrayStringseparator.htm

http://www.java2s.com/Code/JavaAPI/org.apache.commons.lang/StringUtilsjoinObjectarrayStringseparator.htm

回答by coobird

Apache Commons Langdoes indeed have a StringUtils.joinmethod which will connect Stringarrays together with a specified separator.

Apache Commons Lang确实有一种StringUtils.join方法可以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 Stringjoining 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,我可能会自己动手以减少对外部库的依赖项的数量。

回答by nd.

I prefer Google Collectionsover Apache StringUtils for this particular problem:

对于这个特定问题,我更喜欢Google Collections 而不是 Apache StringUtils:

Joiner.on(separator).join(array)

Compared to StringUtils, the Joiner API has a fluent design and is a bit more flexible, e.g. nullelements may be skipped or replaced by a placeholder. Also, Joinerhas a feature for joining maps with a separator between key and value.

与StringUtils 相比,Joiner API 的设计更流畅,更灵活一些,例如null可以跳过元素或用占位符替换元素。此外,Joiner还有一个功能,用于在键和值之间使用分隔符连接映射。

回答by wadjakman

You can use replace and replaceAll with regular expressions.

您可以将 replace 和 replaceAll 与正则表达式一起使用。

String[] strings = {"a", "b", "c"};

String result = Arrays.asList(strings).toString().replaceAll("(^\[|\]$)", "").replace(", ", ",");

Because Arrays.asList().toString()produces: "[a, b, c]", we do a replaceAllto remove the first and last brackets and then (optionally) you can change the ", " sequence for "," (your new separator).

因为Arrays.asList().toString()产生:“[a,b,c]”,我们执行 areplaceAll来删除第一个和最后一个括号,然后(可选)您可以更改“,”序列为“,”(您的新分隔符)。

A stripped version (fewer chars):

剥离版本(更少的字符):

String[] strings = {"a", "b", "c"};

String result = ("" + Arrays.asList(strings)).replaceAll("(^.|.$)", "").replace(", ", "," );

Regular expressions are very powerful, specially String methods "replaceFirst" and "replaceAll". Give them a try.

正则表达式非常强大,特别是字符串方法“replaceFirst”和“replaceAll”。给他们一个尝试。

回答by Ajax

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

我会给你零开销的最优算法;它看起来不像其他选项那么漂亮,但在内部,这就是他们都在做的事情(在一堆其他隐藏检查、多个数组分配和其他 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);
}

回答by Zedas

A fast and simple solution without any 3rd party includes.

一个快速简单的解决方案,没有任何 3rd 方包括在内。

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();
}

回答by eivindw

With Java 1.8 there is a new StringJoiner class- so no need for Guava or Apache Commons:

Java 1.8 有一个新的StringJoiner 类- 所以不需要 Guava 或 Apache Commons:

String str = new StringJoiner(",").add("a").add("b").add("c").toString();

Or using a collection directly with the new stream api:

或者直接使用带有新流 api 的集合:

String str = Arrays.asList("a", "b", "c").stream().collect(Collectors.joining(","));

回答by SSpoke

This small function always comes in handy.

这个小功能总是派上用场。

public static String join(String[] strings, int startIndex, String separator) {
    StringBuffer sb = new StringBuffer();
    for (int i=startIndex; i < strings.length; i++) {
        if (i != startIndex) sb.append(separator);
        sb.append(strings[i]);
    }
    return sb.toString();
}

回答by mnesarco

This options is fast and clear:

此选项快速而清晰:

  public static String join(String separator, String... values) {
    StringBuilder sb = new StringBuilder(128);
    int end = 0;
    for (String s : values) {
      if (s != null) {
        sb.append(s);
        end = sb.length();
        sb.append(separator);
      }
    }
    return sb.substring(0, end);
  }