-2

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 ""

HamZa
  • 14,671
  • 11
  • 54
  • 75

5 Answers5

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"]

Source: Split string into array of character strings

Community
  • 1
  • 1
markieo
  • 484
  • 3
  • 14
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
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