What is the better way to add commas to multiple elements string output?

混江龙づ霸主 提交于 2020-01-15 04:50:30

问题


I need to put comma separated values into ourOutput (for future output). So, what I need is to add commas and remove last unnecessary comma or check if comma should be placed.

I came to two following solutions:

1st approach:

ourOutput  = ''<<'';
for (int i = 0; i< 10, i++) {
  if (/*some condition goes here*/) {
    if (ourOutput.size() == 0) {
      ourOutput << ', '
    } 
    ourOutput << i;
  }
}

pros: don't change resulting string cons: check on each iteration;

2nd approach:

ourOutput  = ''<<'';
for (int i = 0; i< 10, i++) {
  if (/*some condition goes here*/) {
    ourOutput << i << ', ';
  }
}
if (ourOutput.size() != 0) {
  ourOutput.setLength(ourOutput.length() - 2);
} 

pros: don't check each time cons: modifying resulting string.

Please advise, which one to use or maybe there is some better way to do that?

p.s. code written in groovy, feel free to replace ''<<'' with new StringBuilder() and << with .append() so it became java-compilable.


回答1:


There's an excellent library to aid you with this, Commons Lang StringUtils

StringUtils.join(C, ",");

where C can be either a Collection, Array, or Iterator.




回答2:


The lang library of Apache Commons has a nice method for this:

StringUtils.join(java.util.Collection,char)



回答3:


If this is groovy, why not just do:

String ourOutput = (0..9).join( ',' )



回答4:


As it's Groovy code, a concise solution is to store each item in a List then join the List to create a comma-separated string, e.g.

List ourOutput = []

for (int i = 0; i < 10, i++) {
  if (/*some condition goes here*/) {
    ourOutput << i
  }
}

String commaSeparated = ourOutput.join(',')



回答5:


You can do this task in two step:

  • split String variable by one to one character (it means : test ==>> String{"t","e","s","t"})
  • join array reult in above step by Apache Commons Lang3

I write a utility method for this task:

public static String join(String src, String separator)
{
        String[] array = src.split("\\.?");

        String newString = StringUtils.join(array, separator);
        String finalResult = newString.substring(1, newString.length());

        System.out.println(finalResult);

        return finalResult;
}

if you execute this method with two argument as TEST and , you will see following output in console:

T,E,S,T

I hope my answer useful for you.




回答6:


You can use following method to add separator to any array.

Defining joinSeparator()

public static String joinSeparator(Object[] array, char separator) {
        if (array == null) {
            return null;
        }

        int startIndex = 0;
        int endIndex = array.length;

        int bufSize = (endIndex - startIndex);
        if (bufSize <= 0) {
            return null;
        }

        bufSize *= ((array[startIndex] == null ? 16 : array[startIndex]
                .toString().length()) + 1);
        StringBuffer buf = new StringBuffer(bufSize);

        for (int i = startIndex; i < endIndex; i++) {
            if (i > startIndex) {
                buf.append(separator);
            }
            if (array[i] != null) {
                buf.append(array[i]);
            }
        }
        return buf.toString();
    }

Call joinSeparator() method

String[] array = {"sunil", "kumar", "sahoo"};
    joinSeparator(array, ',');


来源:https://stackoverflow.com/questions/9699460/what-is-the-better-way-to-add-commas-to-multiple-elements-string-output

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!