I read this text from file "..1..3", want to split using split(), so that I'll get String[] = {".", ".", "1"...}; But for some reason i loose my 3 and gain a ""
Asked
Active
Viewed 151 times
-2
-
6And how do you do that? – Anders R. Bystrup Apr 25 '14 at 13:39
-
And can you be a little more specific on your input/desired output please? – Giovanni Botta Apr 25 '14 at 13:43
-
Using Java 8, `split("")` will work fine. – Alexis C. Apr 25 '14 at 14:05
5 Answers
1
You will need to use the split() function. That is what you find out. But you can do it this way:
"cat".split("(?!^)");
It will produce this:
array ["c", "a", "t"]
1
You may try to do it this way:
public static void main(String[] args) {
String sample = "Split me if you can";
String[] parts = Arrays.copyOfRange(sample.split(""), 1, sample.length() + 1);
}
OUTPUT:
[S, p, l, i, t, , m, e, , i, f, , y, o, u, , c, a, n]

Harmlezz
- 7,972
- 27
- 35
0
If you want the string split by characters, why not using
char[] chars = mystring.toCharArray();
?
If you really need it as array of strings, add :
String[] strings = new String[chars.length];
for (int i = 0; i < chars.length; ++i) {
strings[i] = String.valueOf(chars[i]);
}

Danstahr
- 4,190
- 22
- 38
-
-
1But why? I don't see the point of bringing the regex machinery into such simple task. – Danstahr Apr 25 '14 at 13:45
-
+1, IMO, this is also a good alternative except that you get a char array instead of a String array. – Alexis C. Apr 25 '14 at 13:47
0
Try this:
String s = "..1..3";
String[] trueResult = new String[s.length()];
System.arraycopy(s.split(""), 1, trueResult, 0, s.length());
System.out.print(Arrays.toString(trueResult));
Output:
[., ., 1, ., ., 3]

Mohsen Kamrani
- 7,177
- 5
- 42
- 66
0
The split()
method doesn't lose anything, check how you read your file into the String
( take care of char encoding , and to not forget the last char
)
Yours

Mohsen Kamrani
- 7,177
- 5
- 42
- 66

hgregoire
- 111
- 1
- 3