I have a String containing a sequence of letters and int numbers A1B12C21D24 I want to create a hashMap with keys the letters from the string and values - the numbers following those letters. So my pairs should be A 1 B 12 C 21 D 24 I am reading the first letter with charAt(0), the number however can be any number of characters so the only idea I came up with is to take the characters one by one to see if they are numbers store it in another int variable which I to consequently multiply by 10 and add the next number, until I reach a letter char again. This however seems like a lot of looping and I was not sure if there is more efficient way to do it
Asked
Active
Viewed 69 times
2 Answers
2
For example you can do it like this:
Map<String, String> map = new HashMap<>();
Pattern pattern = Pattern.compile("(\\D+)(\\d+)");
Matcher matcher = pattern.matcher("A1B12C21D24 ");
while (matcher.find()) {
map.put(matcher.group(1), matcher.group(2));
}
System.out.println(map);
Output:
{A=1, B=12, C=21, D=24}

Planck Constant
- 1,406
- 1
- 17
- 19
1
You could try String[] pairs = InputString.split("(?=[A-Z])")
and then iterate over array with String[] letterAndNumber = pairs[i].split("(?<=[A-Z])")
Then you would just need to save it respectively to HashMap.
More to read about powerful regexp in this answer

Filip_Lechowicz
- 36
- 4