I\'m writing following program to separate characters from a string and assign it to an array.
public class Str {
public static void main(String[] args)
You can use String#toCharArray() method:
String str = "hello";
char[] arr = str.toCharArray();
As for your question, when you split on an empty string, you will get the first element as empty string, because, your string starts with an empty string, and after every character also, there is an empty string.
So, the first split occurs before the first character.
h e l l o
^ ^ ^ ^ ^ ^
"Split location"
The trailing empty strings are discarded, as specified in documentation:
Trailing empty strings are therefore not included in the resulting array.
Have you tried the toCharArray() method from the String
class.
The issue with splitting the String
with this ""
is that ""
matches the first character in the string and therefore you get an empty character.
To verify this claim. You could try str.indexOf("")
. This would give you a value 0. If the argument does not occur as a substring, -1 is returned, according to the documentation.
Like others have noted, using toCharArray()
is the preferred method to do this kind of operation. Since the OP wants to know why the first string is empty when using split("")
, it is because empty string is the first match even before the 1st character is parsed. As per documentation, only trailing empty strings are ignored and not the leading empty strings.
In order to work around this problem you can use negative look behind. So, to use split and ignore the first empty string your regex should be:
str.split("(?<!^)")