Java中提取字符串中的數(shù)字,可以使用正則表達(dá)式或非正則表達(dá)式的方法。
1.使用正則表達(dá)式
可以使用正則表達(dá)式"\d+"來(lái)匹配字符串中的數(shù)字,并使用Matcher和Pattern類實(shí)現(xiàn)。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ExtractNumbersFromString {
public static void main(String[] args) {
String str = "有12只貓和13只狗。";
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group());
}
}
}
2.非正則表達(dá)式方法
使用Java中的Character類中的isDigit()方法來(lái)判斷當(dāng)前字符是否為數(shù)字,并在字符串中進(jìn)行遍歷。
public class ExtractNumbersFromString {
public static void main(String[] args) {
String str = "有12只貓和13只狗。";
StringBuilder sb = new StringBuilder();
for (char c : str.toCharArray()) {
if (Character.isDigit(c)) {
sb.append(c);
}
}
System.out.println(sb.toString());
}
}
運(yùn)行上述代碼,即可從字符串中提取數(shù)字并輸出。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-611019.html
?文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-611019.html
到了這里,關(guān)于java 如何字符串中提取數(shù)字,這個(gè)方法真的很不錯(cuò)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!