Java中如何实现三种判断字符串是否为数字的方法?

2026-05-20 23:141阅读0评论SEO资源
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计136个文字,预计阅读时间需要1分钟。

Java中如何实现三种判断字符串是否为数字的方法?

1. 使用Java自带的函数判断字符串是否为数字:javapublic static boolean isNumeric(String str) { for (int i=str.length(); --i >=0;) { if (!Character.isDigit(str.charAt(i))) { return false; } } return true;}

2. 使用正则表达式判断字符串是否为数字:javapublic static boolean isNumeric(String str) { return str.matches(-?\\d+(\\.\\d+)?);}

Java中如何实现三种判断字符串是否为数字的方法?

1用JAVA自带的函数 public static boolean isNumeric(String str){ for (int i = str.length();--i>=0;){ if (!Character.isDigit(str.charAt(i))){ return false; } } return true; } 2用正则表达式 public static boolean isNumeric(String str){ Pattern pattern = Pattern.compile("[0-9]*"); return pattern.matcher(str).matches(); } 3用ascii码 public static boolean isNumeric(String str){ for(int i=str.length();--i>=0;){ int chr=str.charAt(i); if(chr<48 || chr>57) return false; } return true; }
标签:三种

本文共计136个文字,预计阅读时间需要1分钟。

Java中如何实现三种判断字符串是否为数字的方法?

1. 使用Java自带的函数判断字符串是否为数字:javapublic static boolean isNumeric(String str) { for (int i=str.length(); --i >=0;) { if (!Character.isDigit(str.charAt(i))) { return false; } } return true;}

2. 使用正则表达式判断字符串是否为数字:javapublic static boolean isNumeric(String str) { return str.matches(-?\\d+(\\.\\d+)?);}

Java中如何实现三种判断字符串是否为数字的方法?

1用JAVA自带的函数 public static boolean isNumeric(String str){ for (int i = str.length();--i>=0;){ if (!Character.isDigit(str.charAt(i))){ return false; } } return true; } 2用正则表达式 public static boolean isNumeric(String str){ Pattern pattern = Pattern.compile("[0-9]*"); return pattern.matcher(str).matches(); } 3用ascii码 public static boolean isNumeric(String str){ for(int i=str.length();--i>=0;){ int chr=str.charAt(i); if(chr<48 || chr>57) return false; } return true; }
标签:三种