Below is a bit of code which divides an alphanumeric string to a map of numbers and strings (assume numbers are single digits and non-repeating).
Example input:
String alphaNumericStr = "1abcdef2xyz9aaa6xxx";
Output:
Map<Integer, String> map = {1=abcdef, 2=xyz, 9=aaa, 6=xxx}
This is the code i wrote. While it gets the work done, this does not look like a clean solution to me. How can I make this better?
String alphaNumericStr = "1abcdef2xyz9aaa6xxx";
Map<Integer, String> map = new LinkedHashMap<Integer, String>();
Character key = null;
StringBuffer s = new StringBuffer();
for (int i = 0; i < alphaNumericStr.length(); i++) {
Character c = alphaNumericStr.charAt(i);
if (Character.isDigit(c)) {
if (s.length() > 0) {
map.put(Character.getNumericValue(key), s.toString());
s = new StringBuffer();
}
key = c;
} else {
s.append(c);
if (i == alphaNumericStr.length() - 1) {
map.put(Character.getNumericValue(key), s.toString());
}
}
}
System.out.println(map);