Warm tip: This article is reproduced from serverfault.com, please click

Empty string added to string array when splitting for numbers

发布于 2020-11-28 08:41:37

I am currently trying to brush up on Java for university using codebat. My goal is to take a string of any ASCII characters, split all of the numbers from the string, then return the sum of all of the numbers as an int.

For example: foo("abc123xyz") should return 123 and foo("12cd43ad") should return 55

Here is my code:

public int sumNumbers(String str) {
  int sum = 0;
  
  String[] numArr = str.split("\\D+"); //This is my attempted regex
  for (String num: numArr) {
    sum += Integer.parseInt(num);
  }
  
  return sum;
}

When I run sumNumbers("abc123xyz") or sumNumbers("aa11b33"), I get this error:

NumberFormatException: For input string: ""

Why is there an empty string in my numArr, and what is the proper regex to solve this issue?

Questioner
bulldogs586
Viewed
0
Qwer Izuken 2020-11-28 18:13:13

Matcher is more applicable for this purpose then split:

int sum = 0;
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(str);
while(m.find()) {
    sum+=Integer.parseInt(m.group());
}
return sum;