Home > Net >  How can an array be printed as a string in java without using any standard library functions like rr
How can an array be printed as a string in java without using any standard library functions like rr

Time:04-19

i need to write a method to print an array as a string ,

for example : int[] example = {1,2,3,4,5};

System.out.println(arrayToString(example));

output : [1, 2, 3, 4, 5]

CodePudding user response:

Quick example:

int[] example = {1,2,3,4,5};
System.out.println(arrayToString(example));

With the helper function:

public static String arrayToString(int[] arr) {
    String output = "[";
    for(int i=0; i<arr.length; i  ) {
        output = output   arr[i];
        if (i<(arr.length-1)) {
            output = output   ", ";
        } 
    }
    return output   "]";
}

There are more efficient ways to handle the building of the String, but this is the bare bones method, which is easy enough for beginners to understand.

CodePudding user response:

You can use StringJoiner to join the string with a delimiter. Try the below function:

private static String arraytoString(int[] arr) {
    StringJoiner stringJoiner = new StringJoiner(",");
    for (int i : arr) {
        stringJoiner.add(String.valueOf(i));
    }
    return "["   stringJoiner   "]";
}

Example uses:

int[] example = {1, 2, 3, 4, 5};
System.out.println(arraytoString(example));
  •  Tags:  
  • java
  • Related