【校招笔试面试之字符串处理】在字符串中找出连续最长的数字串。

 
 
package com.zifuchuan;

import java.util.Scanner;

/**
 * 题目:在字符串中找出连续最长的数字串。
 * 示例:
 *      输入
        abcd12345ed125ss123058789
        输出
        123058789,9
 * 思路1:1.读入字符串,并存储在数组或者String对象中
 *        2.利用Split()方法切分,利用正则表达式匹配字符串中的数字
 */
public class zifuchuan {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);//扫描器
        while (in.hasNext()) {
            String str = in.nextLine();//1.读入字符串并存储在String对象中
            String[] arr = str.split("\\D+");//2.利用Split()方法切分,利用正则表达式匹配字符串中的数字,并将切分内容存入数据串数组中
            String sss = arr[0];//3.将第一组正则匹配的结果转存给sss
            int max = arr[0].length();//4.假设第一组的结果长度最长
            for (int i = 1; i < arr.length; i++) {//5.寻找最长的长度
                if (arr[i].length() > max) {
                    sss = arr[i];
                    max = arr[i].length();
                } else if (arr[i].length() == max) {
                    sss += arr[i];
                }
            }
            System.out.println(sss + "," + max);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/shengmingqijiquan/article/details/77296141