If you are looking for solution without using Java String
functionality (i.e. split
, match
, etc.) then the following should help:
List<String> splitString(String string) {
List<String> list = new ArrayList<String>();
String token = "";
char curr;
for (int e = 0; e < string.length() + 1; e++) {
if (e == 0)
curr = string.charAt(0);
else {
curr = string.charAt(--e);
}
if (isNumber(curr)) {
while (e < string.length() && isNumber(string.charAt(e))) {
token += string.charAt(e++);
}
list.add(token);
token = "";
} else {
while (e < string.length() && !isNumber(string.charAt(e))) {
token += string.charAt(e++);
}
list.add(token);
token = "";
}
}
return list;
}
boolean isNumber(char c) {
return c >= '0' && c <= '9';
}
This solution will split numbers and 'words', where 'words' are strings that don't contain numbers. However, if you like to have only 'words' containing English letters then you can easily modify it by adding more conditions (like isNumber
method call) depending on your requirements (for example you may wish to skip words that contain non English letters). Also note that the splitString
method returns ArrayList
which later can be converted to String
array.