Home > Java > javaTutorial > body text

How to check if a string contains only numbers in Java?

王林
Release: 2023-04-20 19:22:06
forward
2119 people have browsed it

如何检查字符串中只包含数字

有一种很傻的解法,就是用 Long.parseLong(string) 对字符串强转,如果转不成整形,那肯定不是只包含数字,对吧?

但这种方法也太不可取了,所以还得换一种巧妙的,就是使用正则表达式。

public class CheckIfStringContainsDigitsOnly {     public static void main(String[] args) {         digitsOnlyString("123 沉默王二");         digitsOnlyString("123");      }      private static void digitsOnlyString(String string) {         if (string.matches("\\d+")) {             System.out.println("只包含数字的字符串:" + string);         }     } }
Copy after login

输出结果如下所示:

只包含数字:123
Copy after login

The above is the detailed content of How to check if a string contains only numbers in Java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template