简体   繁体   中英

Java print a huge string array as it is

There is a string array, row[] , I want to put delimiters between them. I want to keep the order, so for example if

row[0] was "Gold",
row[1] was "Costly", 
row[2] was NULL,
row[3] was NULL, 
row[5] was "Bronze", 
row[6] was "Cheaper", 

I want to retain the NULL values when I put a delimiter, say \\t in the string array. So my new string should look like

'Gold \t Costly \t \t Bronze \t Cheaper'. 

I can do something like

'System.out.println(row[0] + "\t" + row[1] +"\t" +row[2]+.......' 

but the problem is the string array is more than 120 in length. Is there a better way to do this? (I can't use a for loop, since I'm out putting this in a mapper with other stuff). If it is String.format(), can you tell me how to do it?

There's nothing in the standard API for this. There are several third-party packages that have a "join" method that does what you want (and then some). A particularly nice one is Guava's Joiner . (Per Tim's comment, the StringUtils.join() method in the Apache Commons Lang library also does everything you need.) Using a good third-party library can make a lot of these coding problems go away.

If you don't want (or are not allowed) to use a third-party library, you can write a method to concatenate the elements using the delimiter of your choice:

public static String join(String[] data, String delimiter) {
    StringBuilder sb = new StringBuilder();
    if (data != null && data.length > 0) {
        for (String item : data) {
            sb.append(String.valueOf(item);
            sb.append(delimiter);
        }
        // chop off the last delimiter
        sb.setLength(sb.length() - delimiter.length());
    }
    return sb.toString();
}

Then you can use join() wherever you were going to use your string concatenation expression. For example:

System.out.println(join(row, "\t"));

You should use a for loop then:

String[] row = {"123",null,"ABC"};
StringBuilder sb = new StringBuilder();
for(String s : row){
  if(s != null){
    sb.append(s);
  }

  sb.append("\t");
}
System.out.println("Your result string : "+sb.toString());

This prints:

Your result string : 123        ABC 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM