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

前端 未结 30 2208
耶瑟儿~
耶瑟儿~ 2020-11-22 05:36

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 i

30条回答
  •  [愿得一人]
    2020-11-22 06:35

    With Java 5 variable args, so you don't have to stuff all your strings into a collection or array explicitly:

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

提交回复
热议问题