简体   繁体   中英

(JAVA) array into multi-line string

Having quite a lot of trouble with returning an array as a multi line string. let's say we have this:

Town arrayTown[] = new Town[Constants.MAX_TOWNS];

assume we add values to arrayTown.

public String toString(){

how do you go about returning every object in the array as a string, skipping a line between every object?

Town arrayTown[] = new Town[Constants.MAX_TOWNS];

public String toString(){
String res = "";
for(Town i : arrayTown) {
    res+= i + "\n\n";
}
return res;
}

Should work. If you have any questions let me know.

You can try \\r\\n to append at the end of each string ,because The linefeed character \\n is not the line separator in certain operating systems(like windows). below is the sample code.

String[] arr;
        arr = new String[5];
        arr[0] = "Hai";
        arr[1] = "how are you";
        arr[2] = "I am Fine";
        arr[3] = "What about you";
        arr[4] = "ok,bye";
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < arr.length; i++)
        {
            sb.append(arr[i]+"\r\n ");
        }

        System.out.println("String is:"+sb.toString());

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