How to print the results of a split in Java

10,002

Solution 1

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  

Solution 2

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.

Solution 3

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]);
}
Share:
10,002
Admin
Author by

Admin

Updated on June 14, 2022

Comments

  • Admin
    Admin almost 2 years

    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);
        }
    }
    
  • Ted Hopp
    Ted Hopp over 11 years
    That won't print the last element. You need b.length instead of b.length - 1 (or else <= instead of <).
  • Ted Hopp
    Ted Hopp over 11 years
    Did you try using asList? I don't think it does what you think.
  • Sumit Singh
    Sumit Singh over 11 years
    Yes it will return List and if you print it then it will print all the element because of lists toString method.
  • Ted Hopp
    Ted Hopp over 11 years
    There is no toString() method specified in the List interface. Your code only works because the List that Arrays.toList returns happens to be a subclass of AbstractCollection, which does implement toString the way you want. There's nothing in the specification of Arrays.asList that requires that the returned list be a subclass of AbstractCollection or that the List that is returned override the toString method inherited from Object.