简体   繁体   中英

How to read an int number from a string containing numbers and letters?

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

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}

You could try String[] pairs = InputString.split("(?=[AZ])") and then iterate over array with String[] letterAndNumber = pairs[i].split("(?<=[AZ])")

Then you would just need to save it respectively to HashMap.

More to read about powerful regexp in this answer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM