Reputation: 59
I'm trying to split() a String with no whitespaces, but getting a blank at [0].
String s = "..1..3..";
String[] result2 = s.split("");
System.out.println(result2[0]); // giving me a blank space
I'v realized that "" might not be the right one, but cant find a alternative. Is it possible to split on something else, or will I always get this whitespace when using split() this way?
EDIT SOLUTION:
StringBuilder response = new StringBuilder();
while((i = in.read()) != -1){
response.append((char)i);
}
result = response.toString();
result = result.replace("\n", "").replace("\r", "");
Upvotes: 2
Views: 276
Reputation: 425013
Your regex splits at every position in the input, including the first position, which is at the start of input - before the first character. The first element found then is what's between the start of input and the first character, which is of course a zero-length string - a blank.
However you don't need special code to handle this. To get every character in a String
as String[]
, you need to use this regex:
String[] chars = input.split("(?<=.)";
This regex is a look behind that means "after every character".
Upvotes: 3
Reputation: 14361
Why not just String.toCharArray();
then cast that array to String[]
if you really need it to be String[] type, otherwise char[] looks to be exactly what you're trying to do, except you wont wind up with those funny empty strings in element 0 and 9.
Upvotes: 0
Reputation: 2886
You can use the charAt()
method to do what you did.
If you do it in your way, you may need to remove the first element of the returned array. One way to do this is using Arrays.copyOfRange()
.
String[] newArr = Arrays.copyOfRange(oldArr, 1, oldArr.length);
Upvotes: 0
Reputation: 48817
0
contains the data from the beginning of the string to the first dot (i.e. an empty string)1
contains the first dot2
contains the second dot3
contains the string 1
Upvotes: 3