读入一个字符串str,输出字符串str中的连续最长的数字串

思路:定义一个maxLength变量用来存储最长的数字串的个数,定义一个count用来记录遍历过程中数字个数,如果count大于maxLength,将maxLength的值更改为count,定义一个end变量,用来存储数字串的最后一个数字的位置,最后只需要用字符串的subtring()方法截取字符串就行了。

class Main{
	public static void main(String[] args) {
		Scanner in=new Scanner(System.in);
		int maxLength=0;//记录最长的数字的串的长度
		int count=0;//记录连续数字的个数
		int end=0;//记录数字结束的位置
		String s=null;
		while(in.hasNext()){
			s=in.nextLine();
			for(int i=0;i<s.length();++i){
				if(s.charAt(i)>='0'&&s.charAt(i)<='9'){
					end=i;
					count++;
					if(count>maxLength){
						maxLength=count;
					}
					
				}else{
					count=0;
				}
			}
		}
		System.out.println(s.substring(end-maxLength+1,end+1));
		
	}
}

猜你喜欢

转载自blog.csdn.net/qq_36795474/article/details/81207796