Extract integers from string and add them in Java [duplicate]

我与影子孤独终老i 提交于 2021-02-16 15:25:06

问题


I want to extract the integers from string and add them.

Ex :

String s="ab34yuj789km2";

I should get the output of integers from it as 825 ( i.e., 34 + 789 + 2 = 825 )


回答1:


Here's one way, by using String.split:

public static void main(String[] args) {
    String s="ab34yuj789km2";
    int total = 0;
    for(String numString : s.split("[^0-9]+")) {
        if(!numString.isEmpty()) {
            total += Integer.parseInt(numString);
        }
    }
    // Print the result
    System.out.println("Total = " + total);
}

Note the pattern "[^0-9]+" is a regular expression. It matches one or more characters that are not decimal numbers. There is also a pattern \d for decimal numbers.




回答2:


You can extract the number from string by using regex.

    Pattern pattern = Pattern.compile("\\d+");
    Matcher matcher = pattern.matcher("ab34yuj789km2");
    Integer sum = 0;
    while(matcher.find()) {
       sum += Integer.parseInt(matcher.group());
    }



回答3:


With Java 8:

String str = "ab34yuj789km2";
int sum = Arrays.stream(str.split("\\D+"))
    .filter(s -> !s.isEmpty())
    .mapToInt(s -> Integer.parseInt(s))
    .sum();


来源:https://stackoverflow.com/questions/41013747/extract-integers-from-string-and-add-them-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!