如果不为空或null,请加入逗号 [英] Join comma if not empty or 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. :)
这篇关于如果不为空或null,请加入逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文