Reputation: 5781
I am trying to split a string of 10 numbers and (possibly) letters up and place them into an array. I know that the best way to do this is by using the .split() function that Java offers. I usually don't have a problem with it. However, I am now having trouble with it in a program I am creating. As seen in the code below, I am trying to split the string at every character. The length of the array should therefore be 10. However, the .split("") function is counting the beginning of the string as blank space. This is causing a problem with the rest of the program as there is no element in that index of the array. How can I stop this from happening?
String input = "123456789x";
String[] inputArr = input.split("");
System.out.println("Length: " + inputArr.length);
for(int i=0;i<inputArr.length;i++){
System.out.println(inputArr[i]);
}
This code produces the following result:
Length: 11
(blank index. Not actually in output, its there so you can see. It would otherwise be a blank space)
1
2
3
4
5
6
7
8
9
x
Upvotes: 0
Views: 212
Reputation: 124215
Empty string at start of result is correct (unfortunately) behaviour because each string has empty string before and after it and by using split("")
you decided to split on empty string. In other words
"foo"
will be split in places marked with |
"|f|o|o|"
which will at first generate array
["", "f", "o", "o", ""]
but since split
by default also removes trailing empty strings it returns array without last empty string, but leaves the one in front
["", "f", "o", "o"]
This behaviour was improved in Java 8 so there "foo".split("")
returns ["f", "o", "o"]
but if you want to get same results in pre Java 8 versions you need to explicitly say that you want to split on each empty string except the one which has start of the string after/before it. To do it you can use look-around like
yourString.split("(?!^)");
Other alternative is instead of String[]
array using char[]
array which will hold characters from string. To get such array you can simply invoke:
char[] letters = yourString.toCharArray();
Upvotes: 2