英文:
How to read an int number from a string containing numbers and letters?
问题
我有一个包含字母和整数数字序列的字符串A1B12C21D24,我想创建一个哈希映射,其中键是字符串中的字母,值是跟随这些字母的数字。所以我的键值对应该是:
A 1
B 12
C 21
D 24
我使用charAt(0)读取第一个字母,但数字可以是任意数量的字符,所以我想到的唯一办法是逐个字符地查看它们是否为数字,并将其存储在另一个int变量中,然后乘以10并加上下一个数字,直到我再次遇到字母字符。但这似乎需要很多循环,我不确定是否有更高效的方法。
英文:
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
答案1
得分: 2
例如,您可以像这样操作:
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);
输出结果:
{A=1, B=12, C=21, D=24}
英文:
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}
答案2
得分: 1
你可以尝试使用以下代码:String[] pairs = InputString.split("(?=[A-Z])")
,然后使用String[] letterAndNumber = pairs[i].split("(?<=[A-Z])")
遍历数组。
然后你只需要将它们分别保存到HashMap中。
更多关于强大正则表达式的信息可以在这个答案中阅读。
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论