Leo
Leo

Reputation: 1809

java split () method

I've got a string '123' (yes, it's a string in my program). Could anyone explain, when I use this method:

String[] str1Array =  str2.split(" ");

Why I got str1Array[0]='123' rather than str1Array[0]=1?

Upvotes: 0

Views: 37746

Answers (8)

ErezN
ErezN

Reputation: 699

Try this:

String str = "123"; String res = str.split("");

will return the following result:

1,2,3

Upvotes: 0

Achintya Jha
Achintya Jha

Reputation: 12843

str2.split("") ;

Try this:to split each character in a string . Output:

[, 1, 2, 3]

but it will return an empty first value.

str2.split("(?!^)");

Output :

[1, 2, 3]

Upvotes: 3

Edgard Leal
Edgard Leal

Reputation: 2720

To do the "Split" you must use a delimiter, in this case insert a "," between each number

    public static void main(String[] args) {
    String[] list = "123456".replaceAll("(\\d)", ",$1").substring(1)
            .split(",");
    for (String string : list) {
        System.out.println(string);
    }
}

Upvotes: 1

Darren
Darren

Reputation: 70776

str2 does not contain any spaces, therefore split copies the entire contents of str2 to the first index of str1Array.

You would have to do:

 String str2 = "1 2 3";
 String[] str1Array =  str2.split(" ");

Alternatively, to find every character in str2 you could do:

for (char ch : str2.toCharArray()){
    System.out.println(ch);
}

You could also assign it to the array in the loop.

Upvotes: 3

Tom
Tom

Reputation: 16208

This is because the split() method literally splits the string based on the characters given as a parameter.

We remove the splitting characters and form a new String every time we find the splitting characters.

String[] strs =  "123".split(" ");

The String "123" does not have the character " " (space) and therefore cannot be split apart. So returned is just a single item in the array - { "123" }.

Upvotes: 1

codeMan
codeMan

Reputation: 5758

the regular expression that you pass to the split() should have a match in the string so that it will split the string in places where there is a match found in the string. Here you are passing " " which is not found in '123' hence there is no split happening.

Upvotes: 2

Renjith
Renjith

Reputation: 3274

Simple...You are trying to split string by space and in your string "123", there is no space

Upvotes: 1

Tedil
Tedil

Reputation: 1933

Because there's no space in your String. If you want single chars, try char[] characters = str2.toCharArray()

Upvotes: 1

Related Questions