讀入一個字符串str,輸出字符串str中的連續最長的數字串 例如輸入:ab123456cde123 則輸出是:123456
思路:首先用toCharArray()方法來把字符串拆成數字,然後定義i遍歷數組,如果a[i]是數字,則再定義j+1同時遍歷,若a[j]也是數字,則用count記錄長度,count+1,一直遍歷到a[j]不是數字時,循環結束,最後用max保存最大長度,用substring()方法取出最長的 數字字符串,該方法使用是輸入兩個下標,注意是左閉右開,所是(i,j+1)
import java.util.Scanner;
public class Number {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
String A = in.next();
char[] a=A.toCharArray(); //把字符串拆開成數組
int max=0; //定義最大的長度
String result=null; //把最長的數字字符賦給result
for(int i=0;i<A.length();i++){
int count=0;
if(Character.isDigit(a[i])){ //Character.isDigit()方法是用來判斷一個字符是否爲一個整數
for(int j=i+1;j<A.length();j++){
if(Character.isDigit(a[j])){
count++;
if(count>max){
max=count;
result=A.substring(i,j+1); //substring()方法是用來去字符串其中的一段字符串,給定兩個下標,並且該方法是左閉右開的,所以是j+1
}
}else {
break; //如果遇到a[j] 不是數字了,說明連續數字字符串結束,跳出循環,i繼續往後走
}
}
}else{
continue;
}
}
System.out.println(result);
}
}