arrays.toString() custom formatting

泪湿孤枕 提交于 2019-12-24 01:43:08

问题


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))

回答1:


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();
    }



回答2:


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.



来源:https://stackoverflow.com/questions/15818208/arrays-tostring-custom-formatting

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