读入一个字符串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);
}
}