---
title: "demo05——返回字符串第一个数字"
author: "smallearth"
date: "2013-02-12T23:35:00Z"
tags: []
slug: "demo05"
draft: false
lastmod: "2013-11-30T20:10:23Z"
id: 1983288
url: "https://smallearth.iteye.com/blog/1983288"
---

以下的静态方法实现了：把串s中第一个出现的数字的值返回。  
如果找不到数字，返回-1  
例如：  
s = "abc24us43" 则返回2  
s = "82445adb5" 则返回8  
s = "ab" 则返回-1  
public static int getFirstNum(String s)  
{  
if(s==null || s.length()==0) return -1;

char c = s.charAt(0);  
if(c&gt;='0' && c&lt;='9') return \_\_\_\_\_\_\_\_\_\_\_\_\_; //填空

return \_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_; //填空  
}  
请分析代码逻辑，并推测划线处的代码。

答案写在 “解答.txt” 文件中

注意：只写划线处应该填的内容，划线前后的内容不要抄写。

```
public class demo05 {

	public static int getFirstNum(String s)
	{
		if(s==null || s.length()==0) return -1;
		
		char c = s.charAt(0);
		if(c>='0' && c<='9') return c-'0';  //这里c是字符，要把它专换为数字，填空
		
		return getFirstNum(s.substring(1));  //填空
	}
    public static void main(String arg[]){
        String s1 = "0" ; //则返回2
        String s2 = "82445adb5";  //则返回8
    	String s3 = "ab";   //则返回-1   

    	System.out.println(getFirstNum(s1));
    	System.out.println(getFirstNum(s2));
    	System.out.println(getFirstNum(s3));
    }  

}
```

### substring

```
public String substring(intbeginIndex)
```

返回一个新的字符串，它是此字符串的一个子字符串。该子字符串始于指定索引处的字符，一直到此字符串末尾。

例如：

> ```
>  "unhappy".substring(2) returns "happy"
 "Harbison".substring(3) returns "bison"
 "emptiness".substring(9) returns "" (an empty string)
 
> ```

**参数：**

`beginIndex` - 开始处的索引（包括）。

**返回：**

指定的子字符串。

**抛出：**

`IndexOutOfBoundsException` - 如果`beginIndex` 为负或大于此 `String` 对象的长度。