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
?
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
?
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]
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.
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.
Because there's no space in your String
.
If you want single chars, try char[] characters = str2.toCharArray()
Simple...You are trying to split string by space and in your string "123", there is no space
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" }
.
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);
}
}
Try this:
String str = "123"; String res = str.split("");
will return the following result:
1,2,3