如果不为空或null,请加入逗号

如果不为空或null,请加入逗号

问题描述:

我看到这个回答如何将String []连接到逗号分隔的字符串。

I saw this answer of how to join String[] to comma separated string.

但是我需要util来加入数组中的字符串如果值不为空。

However I need the util to join the string in the array only if the values are not empty.

最好的方法是什么?没有循环之前在String []上删除。我更喜欢一种可以同时执行这两种操作的方法。

What is the best way to do it? without looping before on the String[] to remove. I prefer one method that does both.

EDITED

例如:

I, love, , u

将是:

 I love u


public class So20111214a {
    public static String join(String[] argStrings) {
        if (argStrings == null) {
            return "";
        }
        String ret = "";
        if (argStrings.length > 0) {
            ret = argStrings[0];
        } // if
        for (int i = 1; i<argStrings.length; i++) {
            ret += (argStrings[i] == null) 
                    ? "" 
                    : (argStrings[i].isEmpty() 
                        ? "" 
                        :  ( "," + argStrings[i] ) );
        } // for
        return ret;
    } // join() method

    public static void main(String[] args) {
        String[] grandmasters = {  
            "Emanuel Lasker", 
            "José Raúl Capablanca", 
            "Alexander Alekhine", 
            "Siegbert Tarrasch", 
            "Frank Marshall"  
        };
        String[] s1 = null;
        String[] s2 = {};
        String[] s3 = { "Mikhail Botvinnik" };
        System.out.println(join(s1));
        System.out.println(join(s2));
        System.out.println(join(s3));
        System.out.println(join(grandmasters));
        System.out.println(join(new String[]{"I", "love", "", null, "u!"}));
    } // main() method

    /* output:
    <empty string>
    <empty string>
    Mikhail Botvinnik
    Emanuel Lasker,José Raúl Capablanca,Alexander Alekhine,Siegbert Tarrasch,Frank Marshall
    I,love,u!
    */

} // So20111214a class

PS:对不起,请使用?操作员 - 我必须快速完成,我在工作。 :)

PS: Sorry for using the ? operator - I had to do it quickly, I am at work. :)