0

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?

Harry Joy
  • 58,650
  • 30
  • 162
  • 207
Leo
  • 1,787
  • 5
  • 21
  • 43

8 Answers8

3
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]
Achintya Jha
  • 12,735
  • 2
  • 27
  • 39
3

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.

Darren
  • 68,902
  • 24
  • 138
  • 144
2

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.

codeMan
  • 5,730
  • 3
  • 27
  • 51
1

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

Tedil
  • 1,935
  • 28
  • 32
1

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

Renjith
  • 3,274
  • 19
  • 39
1

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" }.

Tom
  • 15,798
  • 4
  • 37
  • 48
1

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);
    }
}
Edgard Leal
  • 2,592
  • 26
  • 30
0

Try this:

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

will return the following result:

1,2,3

ErezN
  • 669
  • 2
  • 13
  • 25