Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print the results of a split in Java

How do I make this print the contents of b rather than its memory address?

public class Testing {
    public static void main (String [] args){
        String a = "A#b#C ";
        String[] b = a.split("#");
        System.out.println(b);
    }
}

2 Answers

You can use Arrays.toString to print the String representation of your array: -

System.out.println(Arrays.toString(b);

This will print your array like this: -

[A, b, C ]

Or, if you want to print each element separately without that square brackets at the ends, you can use enhanced for-loop: -

for(String val: b) {
    System.out.print(val + " ");
}

This will print your array like this: -

A b C  
like image 80
Rohit Jain Avatar answered Dec 08 '25 21:12

Rohit Jain


If you want each element printed on a separate line, you can do this:

public class Testing {
    public static void main (String [] args){
        String a = "A#b#C ";
        String[] b = a.split("#");
        for (String s : b) {
            System.out.println(s);
        }
    }
}

For a result like [A, b, C], use Rohit's answer.

like image 35
Ted Hopp Avatar answered Dec 08 '25 23:12

Ted Hopp