user1212818
user1212818

Reputation:

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

Upvotes: 2

Views: 12880

Answers (3)

Rohit Jain
Rohit Jain

Reputation: 213311

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  

Upvotes: 8

Jericho
Jericho

Reputation: 10953

Please try this

String a = "A#b#C "; 
String[] b = a.split("#"); 

for( int i = 0; i < b.length; i++)
{
System.out.println(b[i]);
}

Upvotes: 1

Ted Hopp
Ted Hopp

Reputation: 234847

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.

Upvotes: 2

Related Questions