2016-12-07 44 views
0

我想從字符串中提取整數並添加它們。從字符串中提取整數並將它們添加到Java中

例:

String s="ab34yuj789km2"; 

我應該得到整數的輸出從它作爲825(即,34 + 789 + 2 = 825)

+5

'javasript' ====='java' –

+4

http://stackoverflow.com/questions/12216065/how-to-extract-numeric-值從輸入字符串在java中 – Guy

+0

@Guy我會推薦這個答案:http://stackoverflow.com/a/12216123/982149在您接受的問題接受的答案。 – Fildor

回答

2

這裏有一種方法,通過使用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); 
} 

注意模式"[^0-9]+"是一個正則表達式。它匹配一個或多個不是十進制數的字符。十進制數也有一個模式\d

+1

它工作。 @Patrick –

+0

很高興聽到@pb_!請不要忘記標記已接受的答案。 –

2

您可以使用正則表達式從字符串中提取數字。

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

這也是@Anh Pham的工作 –

1

與Java 8:

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