如何从包含数字和字母的字符串中读取整数?

huangapple go评论150阅读模式
英文:

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&lt;String, String&gt; map = new HashMap&lt;&gt;();
Pattern pattern = Pattern.compile(&quot;(\\D+)(\\d+)&quot;);
Matcher matcher = pattern.matcher(&quot;A1B12C21D24 &quot;);
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(&quot;(?=[A-Z])&quot;) and then iterate over array with String[] letterAndNumber = pairs[i].split(&quot;(?&lt;=[A-Z])&quot;)

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

More to read about powerful regexp in this answer

huangapple
  • 本文由 发表于 2020年8月5日 16:14:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/63261033.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定