把字符串中第一个出现的数字的值返回

 1 package cn.test;
 2 
 3 /**
 4  * 静态方式:把字符串中第一个出现的数字的值返回
 5  * 
 6  */
 7 public class Test {
 8     public static int getNum(String str) {
 9         if (str == null || str.length() == 0)
10         {
11             return -1;
12         }
13         char c = str.charAt(0);//返回指定索引位置的char值
14         if (c >= '0' && c <= '9') {//这里的c是字符型,返回的要是是int型
15             return c - '0';
16         }
17         return getNum(str.substring(1));//递归调用
18     }
19 
20     public static void main(String[] args) {
21         String str = "abcd1234";
22         System.out.println(getNum(str));
23     }
24 }

 

posted @ 2017-05-01 22:58  李梦晨  阅读(755)  评论(0编辑  收藏  举报