I have a very basic task in java:
Split a string into letters (of type String, not char).
What I used first was String.split("123"), which returned a leading empty space "{,1,2,3}".
Since you need to convert the Array into something else or create a new one to remove the first space – I searched for a good appraoch and found many many variants, but all of them are bulky, like using loops and various conversionos.
So how would you convert a String into a collection of letter Strings?
- by using StringBuffers?
- converting to a ArrayList?
- using split and creating a new Array without leading empty space?
- use Tokenizer?
How does a short, clear approach look like?
My favorite for now is
String[] singleLetters = string.split("");
singleLetters = Arrays.copyOfRange(singleLetters, 1, singleLetters.length);
A better approach is:
String[] singleLetters = string.split("(?!^)")
The regex will prevent the empty string at the beginning from matching, so the result will not contain starting empty string. This solution will work without any assumption.