简体   繁体   English

在 Java 中构建一串分隔项的最佳方法是什么?

[英]What's the best way to build a string of delimited items in Java?

While working in a Java app, I recently needed to assemble a comma-delimited list of values to pass to another web service without knowing how many elements there would be in advance.在使用 Java 应用程序时,我最近需要组装一个以逗号分隔的值列表以传递给另一个 web 服务,而无需事先知道有多少元素。 The best I could come up with off the top of my head was something like this:我能想到的最好的事情是这样的:

public String appendWithDelimiter( String original, String addition, String delimiter ) {
    if ( original.equals( "" ) ) {
        return addition;
    } else {
        return original + delimiter + addition;
    }
}

String parameterString = "";
if ( condition ) parameterString = appendWithDelimiter( parameterString, "elementName", "," );
if ( anotherCondition ) parameterString = appendWithDelimiter( parameterString, "anotherElementName", "," );

I realize this isn't particularly efficient, since there are strings being created all over the place, but I was going for clarity more than optimization.我意识到这不是特别有效,因为到处都在创建字符串,但我的目的是为了清晰而不是优化。

In Ruby, I can do something like this instead, which feels much more elegant:在 Ruby 中,我可以这样做,感觉更优雅:

parameterArray = [];
parameterArray << "elementName" if condition;
parameterArray << "anotherElementName" if anotherCondition;
parameterString = parameterArray.join(",");

But since Java lacks a join command, I couldn't figure out anything equivalent.但由于 Java 缺少连接命令,我想不出任何等效的东西。

So, what's the best way to do this in Java?那么,在 Java 中执行此操作的最佳方法是什么?

Pre Java 8:预 Java 8:

Apache's commons lang is your friend here - it provides a join method very similar to the one you refer to in Ruby: Apache 的 commons lang 在这里是您的朋友 - 它提供了一种与您在 Ruby 中引用的方法非常相似的连接方法:

StringUtils.join(java.lang.Iterable,char)


Java 8: Java 8:

Java 8 provides joining out of the box via StringJoiner and String.join() . Java 8 通过StringJoinerString.join()提供开箱即用的连接。 The snippets below show how you can use them:下面的片段显示了如何使用它们:

StringJoiner

StringJoiner joiner = new StringJoiner(",");
joiner.add("01").add("02").add("03");
String joinedString = joiner.toString(); // "01,02,03"

String.join(CharSequence delimiter, CharSequence... elements))

String joinedString = String.join(" - ", "04", "05", "06"); // "04 - 05 - 06"

String.join(CharSequence delimiter, Iterable<? extends CharSequence> elements)

List<String> strings = new LinkedList<>();
strings.add("Java");strings.add("is");
strings.add("cool");
String message = String.join(" ", strings);
//message returned is: "Java is cool"

You could write a little join-style utility method that works on java.util.Lists您可以编写一个适用于 java.util.Lists 的小连接式实用程序方法

public static String join(List<String> list, String delim) {

    StringBuilder sb = new StringBuilder();

    String loopDelim = "";

    for(String s : list) {

        sb.append(loopDelim);
        sb.append(s);            

        loopDelim = delim;
    }

    return sb.toString();
}

Then use it like so:然后像这样使用它:

    List<String> list = new ArrayList<String>();

    if( condition )        list.add("elementName");
    if( anotherCondition ) list.add("anotherElementName");

    join(list, ",");

In the case of Android, the StringUtils class from commons isn't available, so for this I used在 Android 的情况下,来自 commons 的 StringUtils class 不可用,所以为此我使用了

android.text.TextUtils.join(CharSequence delimiter, Iterable tokens)

http://developer.android.com/reference/android/text/TextUtils.html http://developer.android.com/reference/android/text/TextUtils.html

The Google's Guava library has com.google.common.base.Joiner class which helps to solve such tasks. Google 的 Guava 库com.google.common.base.Joiner class 有助于解决此类任务。

Samples:样品:

"My pets are: " + Joiner.on(", ").join(Arrays.asList("rabbit", "parrot", "dog")); 
// returns "My pets are: rabbit, parrot, dog"

Joiner.on(" AND ").join(Arrays.asList("field1=1" , "field2=2", "field3=3"));
// returns "field1=1 AND field2=2 AND field3=3"

Joiner.on(",").skipNulls().join(Arrays.asList("London", "Moscow", null, "New York", null, "Paris"));
// returns "London,Moscow,New York,Paris"

Joiner.on(", ").useForNull("Team held a draw").join(Arrays.asList("FC Barcelona", "FC Bayern", null, null, "Chelsea FC", "AC Milan"));
// returns "FC Barcelona, FC Bayern, Team held a draw, Team held a draw, Chelsea FC, AC Milan"

Here is an article about Guava's string utilities .这是 一篇关于 Guava 的字符串实用程序的文章。

In Java 8 you can use String.join() :在 Java 8 中,您可以使用String.join()

List<String> list = Arrays.asList("foo", "bar", "baz");
String joined = String.join(" and ", list); // "foo and bar and baz"

Also have a look at this answer for a Stream API example.另请查看 Stream API 示例的此答案

in Java 8 you can do this like:在 Java 8 你可以这样做:

list.stream().map(Object::toString)
        .collect(Collectors.joining(delimiter));

if list has nulls you can use:如果列表有空值,您可以使用:

list.stream().map(String::valueOf)
        .collect(Collectors.joining(delimiter))

it also supports prefix and suffix:它还支持前缀和后缀:

list.stream().map(String::valueOf)
        .collect(Collectors.joining(delimiter, prefix, suffix));

You can generalize it, but there's no join in Java, as you well say.您可以概括它,但正如您所说,Java 中没有加入。

This might work better.可能会更好。

public static String join(Iterable<? extends CharSequence> s, String delimiter) {
    Iterator<? extends CharSequence> iter = s.iterator();
    if (!iter.hasNext()) return "";
    StringBuilder buffer = new StringBuilder(iter.next());
    while (iter.hasNext()) buffer.append(delimiter).append(iter.next());
    return buffer.toString();
}

Use an approach based on java.lang.StringBuilder .使用基于java.lang.StringBuilder的方法。 ("A mutable sequence of characters. ") (“一个可变的字符序列。”)

Like you mentioned, all those string concatenations are creating Strings all over.就像您提到的那样,所有这些字符串连接都在创建字符串。 StringBuilder won't do that. StringBuilder不会那样做。

Why StringBuilder instead of StringBuffer ?为什么使用StringBuilder而不是StringBuffer From the StringBuilder javadoc:来自StringBuilder javadoc:

Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.在可能的情况下,建议优先使用此 class 而不是 StringBuffer,因为它在大多数实现下会更快。

I would use Google Collections.我会使用谷歌 Collections。 There is a nice Join facility.有一个不错的加入设施。
http://google-collections.googlecode.com/svn/trunk/javadoc/index.html?com/google/common/base/Join.html http://google-collections.googlecode.com/svn/trunk/javadoc/index.html?com/google/common/base/Join.ZFC35FDC70D5FC69D2693EZ883A822C7A

But if I wanted to write it on my own,但如果我想自己写,

package util;

import java.util.ArrayList;
import java.util.Iterable;
import java.util.Collections;
import java.util.Iterator;

public class Utils {
    // accept a collection of objects, since all objects have toString()
    public static String join(String delimiter, Iterable<? extends Object> objs) {
        if (objs.isEmpty()) {
            return "";
        }
        Iterator<? extends Object> iter = objs.iterator();
        StringBuilder buffer = new StringBuilder();
        buffer.append(iter.next());
        while (iter.hasNext()) {
            buffer.append(delimiter).append(iter.next());
        }
        return buffer.toString();
    }

    // for convenience
    public static String join(String delimiter, Object... objs) {
        ArrayList<Object> list = new ArrayList<Object>();
        Collections.addAll(list, objs);
        return join(delimiter, list);
    }
}

I think it works better with an object collection, since now you don't have to convert your objects to strings before you join them.我认为它更适合使用 object 集合,因为现在您不必在加入对象之前将它们转换为字符串。

Apache commons StringUtils class has a join method. Apache commons StringUtils class 有一个join方法。

Java 8 Java 8

stringCollection.stream().collect(Collectors.joining(", "));

Java 8 Native Type Java 8 原生型

List<Integer> example;
example.add(1);
example.add(2);
example.add(3);
...
example.stream().collect(Collectors.joining(","));

Java 8 Custom Object: Java 8 定制 Object:

List<Person> person;
...
person.stream().map(Person::getAge).collect(Collectors.joining(","));

Use StringBuilder and class Separator使用 StringBuilder 和 class Separator

StringBuilder buf = new StringBuilder();
Separator sep = new Separator(", ");
for (String each : list) {
    buf.append(sep).append(each);
}

Separator wraps a delimiter.分隔符包裹一个分隔符。 The delimiter is returned by Separator's toString method, unless on the first call which returns the empty string!分隔符由 Separator 的toString方法返回,除非在第一次调用时返回空字符串!

Source code for class Separator class Separator的源代码

public class Separator {

    private boolean skipFirst;
    private final String value;

    public Separator() {
        this(", ");
    }

    public Separator(String value) {
        this.value = value;
        this.skipFirst = true;
    }

    public void reset() {
        skipFirst = true;
    }

    public String toString() {
        String sep = skipFirst ? "" : value;
        skipFirst = false;
        return sep;
    }

}

And a minimal one (if you don't want to include Apache Commons or Gauva into project dependencies just for the sake of joining strings)还有一个最小的(如果您不想为了加入字符串而将 Apache Commons 或 Gauva 包含到项目依赖项中)

/**
 *
 * @param delim : String that should be kept in between the parts
 * @param parts : parts that needs to be joined
 * @return  a String that's formed by joining the parts
 */
private static final String join(String delim, String... parts) {
    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < parts.length - 1; i++) {
        builder.append(parts[i]).append(delim);
    }
    if(parts.length > 0){
        builder.append(parts[parts.length - 1]);
    }
    return builder.toString();
}

You can use Java's StringBuilder type for this.您可以为此使用 Java 的StringBuilder类型。 There's also StringBuffer , but it contains extra thread safety logic that is often unnecessary.还有StringBuffer ,但它包含通常不必要的额外线程安全逻辑。

If you're using Eclipse Collections , you can use makeString() or appendString() .如果您使用的是Eclipse Collections ,则可以使用makeString()appendString()

makeString() returns a String representation, similar to toString() . makeString()返回一个String表示,类似于toString()

It has three forms它具有三个 forms

  • makeString(start, separator, end)
  • makeString(separator) defaults start and end to empty strings makeString(separator)默认开始和结束为空字符串
  • makeString() defaults the separator to ", " (comma and space) makeString()默认分隔符为", " (逗号和空格)

Code example:代码示例:

MutableList<Integer> list = FastList.newListWith(1, 2, 3);
assertEquals("[1/2/3]", list.makeString("[", "/", "]"));
assertEquals("1/2/3", list.makeString("/"));
assertEquals("1, 2, 3", list.makeString());
assertEquals(list.toString(), list.makeString("[", ", ", "]"));

appendString() is similar to makeString() , but it appends to an Appendable (like StringBuilder ) and is void . appendString()类似于makeString() ,但它附加到Appendable (如StringBuilder )并且是void It has the same three forms, with an additional first argument, the Appendable.它具有相同的三个 forms,还有一个附加的第一个参数,即 Appendable。

MutableList<Integer> list = FastList.newListWith(1, 2, 3);
Appendable appendable = new StringBuilder();
list.appendString(appendable, "[", "/", "]");
assertEquals("[1/2/3]", appendable.toString());

If you can't convert your collection to an Eclipse Collections type, just adapt it with the relevant adapter.如果您无法将您的收藏转换为 Eclipse Collections 类型,只需使用相关适配器对其进行调整。

List<Object> list = ...;
ListAdapter.adapt(list).makeString(",");

Note: I am a committer for Eclipse collections.注意:我是 Eclipse collections 的提交者。

If you are using Spring MVC then you can try following steps.如果您使用的是 Spring MVC,那么您可以尝试以下步骤。

import org.springframework.util.StringUtils;

List<String> groupIds = new List<String>;   
groupIds.add("a");    
groupIds.add("b");    
groupIds.add("c");

String csv = StringUtils.arrayToCommaDelimitedString(groupIds.toArray());

It will result to a,b,c这将导致a,b,c

Why not write your own join() method?为什么不编写自己的 join() 方法? It would take as parameters collection of Strings and a delimiter String.它将作为参数集合的字符串和分隔符字符串。 Within the method iterate over the collection and build up your result in a StringBuffer.在该方法中迭代集合并在 StringBuffer 中构建您的结果。

For those who are in a Spring context their StringUtils class is useful as well:对于那些在 Spring 上下文中的人,他们的StringUtils class 也很有用:

There are many useful shortcuts like:有许多有用的快捷方式,例如:

  • collectionToCommaDelimitedString(Collection coll) collectionToCommaDelimitedString(Collection coll)
  • collectionToDelimitedString(Collection coll, String delim) collectionToDelimitedString(Collection coll, String delim)
  • arrayToDelimitedString(Object[] arr, String delim) arrayToDelimitedString(Object[] arr, String delim)

and many others.和许多其他人。

This can be helpful if you are not already using Java 8 and you are already in a Spring context.如果您尚未使用 Java 8 并且您已经在 Spring 上下文中,这可能会有所帮助。

I prefer it against the Apache Commons (although very good as well) for the Collection support which is easier like this:我更喜欢它而不是 Apache Commons(虽然也非常好),因为它更容易像这样:

// Encoding Set<String> to String delimited 
String asString = org.springframework.util.StringUtils.collectionToDelimitedString(codes, ";");

// Decoding String delimited to Set
Set<String> collection = org.springframework.util.StringUtils.commaDelimitedListToSet(asString);

You should probably use a StringBuilder with the append method to construct your result, but otherwise this is as good of a solution as Java has to offer.您可能应该使用带有append方法的StringBuilder来构建您的结果,但除此之外,这与 Java 提供的解决方案一样好。

Why don't you do in Java the same thing you are doing in ruby, that is creating the delimiter separated string only after you've added all the pieces to the array?为什么不在 Java 中执行与在 ruby 中相同的操作,即仅在将所有片段添加到数组后创建分隔符分隔字符串?

ArrayList<String> parms = new ArrayList<String>();
if (someCondition) parms.add("someString");
if (anotherCondition) parms.add("someOtherString");
// ...
String sep = ""; StringBuffer b = new StringBuffer();
for (String p: parms) {
    b.append(sep);
    b.append(p);
    sep = "yourDelimiter";
}

You may want to move that for loop in a separate helper method, and also use StringBuilder instead of StringBuffer...您可能希望在单独的辅助方法中移动该 for 循环,并使用 StringBuilder 而不是 StringBuffer ...

Edit : fixed the order of appends.编辑:修复了追加的顺序。

With Java 5 variable args, so you don't have to stuff all your strings into a collection or array explicitly:使用 Java 5 个变量 args,因此您不必将所有字符串显式地填充到集合或数组中:

import junit.framework.Assert;
import org.junit.Test;

public class StringUtil
{
    public static String join(String delim, String... strings)
    {
        StringBuilder builder = new StringBuilder();

        if (strings != null)
        {
            for (String str : strings)
            {
                if (builder.length() > 0)
                {
                    builder.append(delim).append(" ");
                }
                builder.append(str);
            }
        }           
        return builder.toString();
    }
    @Test
    public void joinTest()
    {
        Assert.assertEquals("", StringUtil.join(",", null));
        Assert.assertEquals("", StringUtil.join(",", ""));
        Assert.assertEquals("", StringUtil.join(",", new String[0]));
        Assert.assertEquals("test", StringUtil.join(",", "test"));
        Assert.assertEquals("foo, bar", StringUtil.join(",", "foo", "bar"));
        Assert.assertEquals("foo, bar, x", StringUtil.join(",", "foo", "bar", "x"));
    }
}

using Dollar is simple as typing:使用Dollar很简单,只需键入:

String joined = $(aCollection).join(",");

NB: it works also for Array and other data types注意:它也适用于数组和其他数据类型

Implementation执行

Internally it uses a very neat trick:在内部,它使用了一个非常巧妙的技巧:

@Override
public String join(String separator) {
    Separator sep = new Separator(separator);
    StringBuilder sb = new StringBuilder();

    for (T item : iterable) {
        sb.append(sep).append(item);
    }

    return sb.toString();
}

the class Separator return the empty String only the first time that it is invoked, then it returns the separator: class Separator仅在第一次调用时返回空字符串,然后返回分隔符:

class Separator {

    private final String separator;
    private boolean wasCalled;

    public Separator(String separator) {
        this.separator = separator;
        this.wasCalled = false;
    }

    @Override
    public String toString() {
        if (!wasCalled) {
            wasCalled = true;
            return "";
        } else {
            return separator;
        }
    }
}

Fix answer Rob Dickerson.修复答案 Rob Dickerson。

It's easier to use:它更容易使用:

public static String join(String delimiter, String... values)
{
    StringBuilder stringBuilder = new StringBuilder();

    for (String value : values)
    {
        stringBuilder.append(value);
        stringBuilder.append(delimiter);
    }

    String result = stringBuilder.toString();

    return result.isEmpty() ? result : result.substring(0, result.length() - 1);
}

Slight improvement [speed] of version from izb:来自 izb 的版本略有改进 [速度]:

public static String join(String[] strings, char del)
{
    StringBuilder sb = new StringBuilder();
    int len = strings.length;

    if(len > 1) 
    {
       len -= 1;
    }else
    {
       return strings[0];
    }

    for (int i = 0; i < len; i++)
    {
       sb.append(strings[i]).append(del);
    }

    sb.append(strings[i]);

    return sb.toString();
}

I personally quite often use the following simple solution for logging purposes:我个人经常使用以下简单的解决方案进行日志记录:

List lst = Arrays.asList("ab", "bc", "cd");
String str = lst.toString().replaceAll("[\\[\\]]", "");

If you want to apply comma in a List of object's properties.如果要在对象属性列表中应用逗号。 This is the way i found most useful.这是我发现最有用的方式。

here getName() is a string property of a class i have been trying to add "," to.这里getName()是 class 的字符串属性,我一直在尝试添加“,”。

String message = listName.stream().map(list -> list.getName()).collect(Collectors.joining(", "));字符串消息 = listName.stream().map(list -> list.getName()).collect(Collectors.joining(", "));

You can try something like this:你可以尝试这样的事情:

StringBuilder sb = new StringBuilder();
if (condition) { sb.append("elementName").append(","); }
if (anotherCondition) { sb.append("anotherElementName").append(","); }
String parameterString = sb.toString();

So basically something like this:所以基本上是这样的:

public static String appendWithDelimiter(String original, String addition, String delimiter) {

if (original.equals("")) {
    return addition;
} else {
    StringBuilder sb = new StringBuilder(original.length() + addition.length() + delimiter.length());
        sb.append(original);
        sb.append(delimiter);
        sb.append(addition);
        return sb.toString();
    }
}

Don't know if this really is any better, but at least it's using StringBuilder, which may be slightly more efficient.不知道这是否真的更好,但至少它使用了 StringBuilder,这可能会稍微更有效率。

Down below is a more generic approach if you can build up the list of parameters BEFORE doing any parameter delimiting.如果您可以在进行任何参数定界之前建立参数列表,那么下面是一种更通用的方法。

// Answers real question
public String appendWithDelimiters(String delimiter, String original, String addition) {
    StringBuilder sb = new StringBuilder(original);
    if(sb.length()!=0) {
        sb.append(delimiter).append(addition);
    } else {
        sb.append(addition);
    }
    return sb.toString();
}


// A more generic case.
// ... means a list of indeterminate length of Strings.
public String appendWithDelimitersGeneric(String delimiter, String... strings) {
    StringBuilder sb = new StringBuilder();
    for (String string : strings) {
        if(sb.length()!=0) {
            sb.append(delimiter).append(string);
        } else {
            sb.append(string);
        }
    }

    return sb.toString();
}

public void testAppendWithDelimiters() {
    String string = appendWithDelimitersGeneric(",", "string1", "string2", "string3");
}

Your approach is not too bad, but you should use a StringBuffer instead of using the + sign.您的方法还不错,但您应该使用 StringBuffer 而不是使用 + 号。 The + has the big disadvantage that a new String instance is being created for each single operation. + 有一个很大的缺点,即为每个单独的操作创建一个新的 String 实例。 The longer your string gets, the bigger the overhead.你的字符串越长,开销就越大。 So using a StringBuffer should be the fastest way:所以使用 StringBuffer 应该是最快的方法:

public StringBuffer appendWithDelimiter( StringBuffer original, String addition, String delimiter ) {
        if ( original == null ) {
                StringBuffer buffer = new StringBuffer();
                buffer.append(addition);
                return buffer;
        } else {
                buffer.append(delimiter);
                buffer.append(addition);
                return original;
        }
}

After you have finished creating your string simply call toString() on the returned StringBuffer.完成创建字符串后,只需在返回的 StringBuffer 上调用 toString()。

Instead of using string concatenation, you should use StringBuilder if your code is not threaded, and StringBuffer if it is.如果您的代码不是线程化的,则应该使用 StringBuilder,如果是,则应使用 StringBuffer,而不是使用字符串连接。

You're making this a little more complicated than it has to be.你让这变得比它必须的复杂一点。 Let's start with the end of your example:让我们从示例的结尾开始:

String parameterString = "";
if ( condition ) parameterString = appendWithDelimiter( parameterString, "elementName", "," );
if ( anotherCondition ) parameterString = appendWithDelimiter( parameterString, "anotherElementName", "," );

With the small change of using a StringBuilder instead of a String, this becomes:随着使用 StringBuilder 而不是 String 的微小变化,这变为:

StringBuilder parameterString = new StringBuilder();
if (condition) parameterString.append("elementName").append(",");
if (anotherCondition) parameterString.append("anotherElementName").append(",");
...

When you're done (I assume you have to check a few other conditions as well), just make sure you remove the tailing comma with a command like this:完成后(我假设您还必须检查其他一些条件),只需确保使用以下命令删除尾逗号:

if (parameterString.length() > 0) 
    parameterString.deleteCharAt(parameterString.length() - 1);

And finally, get the string you want with最后,得到你想要的字符串

parameterString.toString();

You could also replace the "," in the second call to append with a generic delimiter string that can be set to anything.您还可以将第二次调用 append 中的“,”替换为可以设置为任何内容的通用分隔符字符串。 If you have a list of things you know you need to append (non-conditionally), you could put this code inside a method that takes a list of strings.如果您有一个您知道需要 append 的东西的列表(无条件),您可以将此代码放在一个采用字符串列表的方法中。

//Note: if you have access to Java5+, 
//use StringBuilder in preference to StringBuffer.  
//All that has to be replaced is the class name.  
//StringBuffer will work in Java 1.4, though.

appendWithDelimiter( StringBuffer buffer, String addition, 
    String delimiter ) {
    if ( buffer.length() == 0) {
        buffer.append(addition);
    } else {
        buffer.append(delimiter);
        buffer.append(addition);
    }
}


StringBuffer parameterBuffer = new StringBuffer();
if ( condition ) { 
    appendWithDelimiter(parameterBuffer, "elementName", "," );
}
if ( anotherCondition ) {
    appendWithDelimiter(parameterBuffer, "anotherElementName", "," );
}

//Finally, to return a string representation, call toString() when returning.
return parameterBuffer.toString(); 

Don't use join, delimiter or StringJoiner methods and classes as they wont work below Android N and O versions.不要使用 join、delimiter 或 StringJoiner 方法和类,因为它们在 Android N 和 O 版本下不起作用。 Else use a simple code logic as;否则使用简单的代码逻辑作为;

 List<String> tags= emp.getTags();
        String tagTxt="";
        for (String s : tags) {
            if (tagTxt.isEmpty()){
                tagTxt=s;
            }else
                tagTxt= tagTxt+", "+s;
        }  

So a couple of things you might do to get the feel that it seems like you're looking for:因此,您可能会做一些事情来获得您正在寻找的感觉:

1) Extend List class - and add the join method to it. 1) 扩展列表 class - 并向其中添加连接方法。 The join method would simply do the work of concatenating and adding the delimiter (which could be a param to the join method) join 方法将简单地完成连接和添加分隔符的工作(这可能是 join 方法的参数)

2) It looks like Java 7 is going to be adding extension methods to java - which allows you just to attach a specific method on to a class: so you could write that join method and add it as an extension method to List or even to Collection. 2) 看起来 Java 7 将向 java 添加扩展方法 - 这允许您将特定方法附加到 class 上,甚至可以将其添加为方法方法以加入或添加方法:收藏。

Solution 1 is probably the only realistic one, now, though since Java 7 isn't out yet:) But it should work just fine.现在,解决方案 1 可能是唯一现实的解决方案,尽管由于 Java 7 还没有推出:) 但它应该可以正常工作。

To use both of these, you'd just add all your items to the List or Collection as usual, and then call the new custom method to 'join' them.要使用这两者,您只需像往常一样将所有项目添加到列表或集合中,然后调用新的自定义方法来“加入”它们。

public static String join(String[] strings, char del)
{
    StringBuffer sb = new StringBuffer();
    int len = strings.length;
    boolean appended = false;
    for (int i = 0; i < len; i++)
    {
        if (appended)
        {
            sb.append(del);
        }
        sb.append(""+strings[i]);
        appended = true;
    }
    return sb.toString();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从java中的列表构建分隔字符串的最佳方法 - Best way to build a delimited string from a list in java 在Java中拆分非定界字符串的好方法是什么? - What's a good way to split a non-delimited string in Java? 检查 String 是否包含 Java/Android 中的 URL 的最佳方法是什么? - What's the best way to check if a String contains a URL in Java/Android? 在 Java 中检查 String 是否代表整数的最佳方法是什么? - What's the best way to check if a String represents an integer in Java? 使用 Java 保护查询字符串的最佳方法是什么? - What's the best way to secure a query string with Java? 在Java中构建JSON字符串的最快方法是什么? - What's the fastest way to build a JSON string in java? 在Java中,以字符形式“构建”和使用字符串的最快方法是什么? - In Java, what's the fastest way to “build” and use a string, character by character? 用Java构建HTML文件的最佳方法是什么? - What is the best way to build an HTML file with Java? 在Java中,最好的方法是将前100个项目保留在多线程程序中? - In Java, what's the best way to keep top 100 items in a multi-threaded program? 在Java中,从另一个数字字符串中减去1个数字字符串的最佳方法是什么 - In java what's the best way to subtract 1 numeric string from another numeric string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM