我想從字符串中提取整數並添加它們。從字符串中提取整數並將它們添加到Java中
例:
String s="ab34yuj789km2";
我應該得到整數的輸出從它作爲825(即,34 + 789 + 2 = 825)
我想從字符串中提取整數並添加它們。從字符串中提取整數並將它們添加到Java中
例:
String s="ab34yuj789km2";
我應該得到整數的輸出從它作爲825(即,34 + 789 + 2 = 825)
這裏有一種方法,通過使用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
。
它工作。 @Patrick –
很高興聽到@pb_!請不要忘記標記已接受的答案。 –
您可以使用正則表達式從字符串中提取數字。
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher("ab34yuj789km2");
Integer sum = 0;
while(matcher.find()) {
sum += Integer.parseInt(matcher.group());
}
這也是@Anh Pham的工作 –
與Java 8:
String str = "ab34yuj789km2";
int sum = Arrays.stream(str.split("\\D+"))
.filter(s -> !s.isEmpty())
.mapToInt(s -> Integer.parseInt(s))
.sum();
'javasript' ====='java' –
http://stackoverflow.com/questions/12216065/how-to-extract-numeric-值從輸入字符串在java中 – Guy
@Guy我會推薦這個答案:http://stackoverflow.com/a/12216123/982149在您接受的問題接受的答案。 – Fildor