一种反转java String.split()效果的方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/794248/
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-11 19:34:21  来源:igfitidea点击:

A method to reverse effect of java String.split()?

javastringjoinsplit

提问by javaphild

I am looking for a method to combine an array of strings into a delimited String. An opposite to split().

我正在寻找一种将字符串数组组合成分隔字符串的方法。与 split() 相反。

Wanted to ask the forum before I try writing my own (since the JDK has everything)

在我尝试自己编写之前想问问论坛(因为 JDK 拥有一切)

回答by John Topley

There's no method in the JDK for this that I'm aware of. Apache Commons Langhas various overloaded join()methods in the StringUtilsclass that do what you want.

我所知道的 JDK 中没有为此提供任何方法。Apache Commons Langjoin()StringUtils类中有各种重载方法,可以执行您想要的操作。

回答by Bill the Lizard

There are several examples on DZone Snippetsif you want to roll your own that works with a Collection. For example:

如果您想推出自己的适用于 Collection 的DZone Snippets,则有几个示例。例如:

public static String join(AbstractCollection<String> s, String delimiter) {
    if (s == null || s.isEmpty()) return "";
    Iterator<String> iter = s.iterator();
    StringBuilder builder = new StringBuilder(iter.next());
    while( iter.hasNext() )
    {
        builder.append(delimiter).append(iter.next());
    }
    return builder.toString();
}

回答by Azder

I got the following example here

我在这里得到了以下示例

/*
7) Join Strings using separator >>>AB$#$CD$#$EF

 */

import org.apache.commons.lang.StringUtils;

public class StringUtilsTrial {
  public static void main(String[] args) {

    // Join all Strings in the Array into a Single String, separated by $#$
    System.out.println("7) Join Strings using separator >>>"
        + StringUtils.join(new String[] { "AB", "CD", "EF" }, "$#$"));
  }
}

回答by Blair Zajac

Google also provides a joiner class in their Google Collections library:

Google 还在其 Google Collections 库中提供了一个 joiner 类:

Joiner API

连接器 API

Google Collections

谷歌收藏

回答by Sarabjot

Based on all the previous answers:

基于之前的所有答案:

public static String join(Iterable<? extends Object> elements, CharSequence separator) 
{
    StringBuilder builder = new StringBuilder();

    if (elements != null)
    {
        Iterator<? extends Object> iter = elements.iterator();
        if(iter.hasNext())
        {
            builder.append( String.valueOf( iter.next() ) );
            while(iter.hasNext())
            {
                builder
                    .append( separator )
                    .append( String.valueOf( iter.next() ) );
            }
        }
    }

    return builder.toString();
}

回答by Luis

I like this better:

我更喜欢这个:

public String join(Collection<String> strCollection, String delimiter) {
    String joined = "";
    int noOfItems = 0;
    for (String item : strCollection) {
        joined += item;
        if (++noOfItems < strCollection.size())
            joined += delimiter;
    }
    return joined;
}

It is the neatest solution I have found so far. (Don't worry about the use of raw String objects instead of StringBuilder. Modern Java compilers use StringBuilder anyway, but this code is more readable).

这是迄今为止我找到的最简洁的解决方案。(不要担心使用原始 String 对象而不是 StringBuilder。现代 Java 编译器无论如何都使用 StringBuilder,但此代码更具可读性)。

回答by David Howard

You can sneak this functionality out of the Arraysutility package.

您可以从Arrays实用程序包中隐藏此功能。

import java.util.Arrays;
...
    String  delim = ":",
            csv_record = "Field0:Field1:Field2", 
            fields[] = csv_record.split(delim);

    String rebuilt_record = Arrays.toString(fields).replace(", ", delim).replaceAll("[\[\]]", "");

回答by DenTheMan

If you have an int[], Arrays.toString()is the easiest way.

如果你有一个int[],Arrays.toString()是最简单的方法。

回答by Microscotch

This one is not bad too :

这个也不错:

public static String join(String delimitor,String ... subkeys) {
    String result = null;
    if(null!=subkeys && subkeys.length>0) {
        StringBuffer joinBuffer = new StringBuffer(subkeys[0]);
        for(int idx=1;idx<subkeys.length;idx++) {
            joinBuffer.append(delimitor).append(subkeys[idx]);
        }
        result = joinBuffer.toString();
    }
    return result;
}

回答by gavenkoa

I wrote this one:

我写了这个:

public static String join(Collection<String> col, String delim) {
    StringBuilder sb = new StringBuilder();
    Iterator<String> iter = col.iterator();
    if (iter.hasNext())
        sb.append(iter.next());
    while (iter.hasNext()) {
        sb.append(delim);
        sb.append(iter.next());
    }
    return sb.toString();
}

Collectionisn't supported by JSP, so for TLD I wrote:

CollectionJSP 不支持,因此对于 TLD,我写道:

public static String join(List<?> list, String delim) {
    int len = list.size();
    if (len == 0)
        return "";
    StringBuilder sb = new StringBuilder(list.get(0).toString());
    for (int i = 1; i < len; i++) {
        sb.append(delim);
        sb.append(list.get(i).toString());
    }
    return sb.toString();
}

and put to .tldfile:

并放入.tld文件:

<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.1" xmlns="http://java.sun.com/xml/ns/javaee"
    <function>
        <name>join</name>
        <function-class>com.core.util.ReportUtil</function-class>
        <function-signature>java.lang.String join(java.util.List, java.lang.String)</function-signature>
    </function>
</taglib>

and use it in JSP files as:

并在 JSP 文件中使用它作为:

<%@taglib prefix="funnyFmt" uri="tag:com.core.util,2013:funnyFmt"%>
${funnyFmt:join(books, ", ")}