user2007843
user2007843

Reputation: 609

arrays.toString() custom formatting

How can I change the output from

[ua, disclaimer, ok, ua, navigation, fault, ua, fault, previous, ua, fault, previous]

to this

ua, disclaimer, ok ---> ua, navigation, fault ---> ua, fault, previous ---> ua, fault, previous

by varying this print statement

System.out.println(Arrays.toString(arr))

Upvotes: 2

Views: 3764

Answers (2)

radai
radai

Reputation: 24192

by writing your own print method. something like this:

    public static String fancyPrint(Object... array) {
        StringBuilder output = new StringBuilder();
        int total = 0;
        for (Object o : array) {
            output.append(o.toString());
            total+=1;
            if (total%3==0) {
                output.append(" ---> ");
            } else {
                output.append(", ");
            }
        }
        //remove last ", " or " ---> " printed
        if (total%3==0) {
            output.delete(output.length()-" ---> ".length(), output.length());
        } else {
            output.delete(output.length()-", ".length(), output.length());
        }
        return output.toString();
    }

Upvotes: 2

dr. gogo
dr. gogo

Reputation: 1

You could trim your array first by number of elements before converting it into string. So you would run toString() on pieces of array. Now use these smaller strings and print them in the order desirable. If you think for trimming, you have to form new sub-arrays and it would waste memory, you could also just print out the array one member at a time.

Upvotes: 0

Related Questions