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
  • 57,133
  • 30
  • 158
  • 207
Leo
  • 1,719
  • 5
  • 20
  • 41

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,515
  • 2
  • 26
  • 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
  • 66,506
  • 23
  • 132
  • 141
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,530
  • 2
  • 24
  • 50
1

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

Tedil
  • 1,903
  • 30
  • 31
1

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

Renjith
  • 3,187
  • 17
  • 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 Cammann
  • 15,343
  • 4
  • 34
  • 47
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,225
  • 24
  • 30
0

Try this:

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

will return the following result:

1,2,3

ErezN
  • 661
  • 2
  • 11
  • 24