java如何判断字符串中是否含有数字

如题所述

一、算法思想

从字符串的第一个字符开始,逐个判断字符是否是数字,若是数字,说明字符串中包含数字,否则继续判断下一个字符,直到找到数字或到字符串结束也没有发现数字。


二、操作过程

        J a v a    2    E n t e r p r i s e    E d i t i o n
        ^(不是数字)
          ^(不是数字)
            ^(不是数字)
              ^(不是数字)
                  ^(不是数字)
                    ^(是数字,结束)


三、程序代码

public class Main {
public static void main(String[] args) {
System.out.println(containDigit("Java 2 Enterprise Edition"));
}

/**
 * åˆ¤æ–­å­—符串中是否包含数字
 * @param source å¾…判断字符串
 * @return å­—符串中是否包含数字,true:包含数字,false:不包含数字
 */
public static boolean containDigit(String source) {
char ch;
for(int i=0; i<source.length(); i++) {
ch = source.charAt(i);
if(ch >= '0' && ch <= '9') {
return true;
}
}

return false;
}
}


四、运行测试

true
温馨提示:答案为网友推荐,仅供参考
第1个回答  2016-09-23
如果只是判断,可与用Integer.parseInt(String)如果是数字,就没有异常,如果有异常,就不是数字或者用正则表达式 return string.matches("\\d+\\.?\\d*")); 这个语句就是用来判断的 \\d+表示一个或者多个数字\\.? 表示一个或这没有小数点 \\d * 表示0个或者多个数字本回答被提问者采纳
第2个回答  2016-09-23
str.matches("([\\w\\W]*)[0-9]*([\\w\\W]*)")
相似回答