字符串中的提取最长的数字串(只考虑字母与数字)

(第一版)最原始的实现方式:

import java.util.HashMap;
import java.util.Map;

public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		String s = "sdfdsfkuffsdf4353453cgcbcvbcb23ddccvd6777u234424234234fgrrter3345435498549854988895985";
		getString(s);

	}

	public static void getString(String str) {

		StringBuffer strbuf = new StringBuffer();
		int len = str.length();
		Map map = new HashMap();
		int j = 0;
		int x = 0;
		int max = 0;
		int temp = 0;
		Map map2 = new HashMap();
		for (int i = 0; i < len; i++) {
			char c = str.charAt(i);
			// 判断是否是数字
			if (c >= '0' && c <= '9') {
				++x;
				map.put(j, strbuf.append(c));
				System.out.println(j+":"+strbuf.toString()+":"+x);
			} else {
				if (x > 0) {
					temp = x;
					if (max < temp) {
						max = temp;
						map2.put("max", max);
						map2.put(max, j);
					}
					System.out.println(j + " - " + strbuf.toString());
					++j;
					strbuf = new StringBuffer();
					x = 0;
				} 
			}
			//如最后为数字
			if(i == len-1 && x>0){
				temp = x;
				if (max < temp) {
					max = temp;
					map2.put("max", max);
					map2.put(max, j);
				}
				System.out.println(j + " - " + strbuf.toString());
				++j;
				strbuf = new StringBuffer();
				x = 0;
			}
		}
		Integer ig = (Integer) map2.get(map2.get("max"));
		System.out.println("max: " + map2.get("max") + ",vaile: " + map.get(ig));

	}
}


(第二版)优化版本:
public static String getNumByString(String str) {

	if (null == str || "".equals(str)) {
		return null;
	}
	Map<Integer, String> ics = new HashMap<Integer, String>();
	StringBuilder strbur = new StringBuilder();
	char[] chars = str.toCharArray();
	int len = chars.length;
	int x = 0;
	int y = 0;
	int max = 0;
	int indexJ = 0;
	for (int i = 0; i < len; i++) {
		if (Character.isDigit(chars[i])) {
			++x;
			ics.put(y, strbur.append(chars[i]).toString());
		} else {
			if (0 < x) {
				if (max < x) {
					max = x;
					indexJ = y;
				}
				++y;
				strbur = new StringBuilder();
				x = 0;
			}
		}
		if (i == len - 1 && x > 0) {
			if (max < x) {
				max = x;
				indexJ = y;
			}
		}

	}
	return ics.get(indexJ);
}


第三版:

public static String getNumByString2(String str){
	if (null == str || "".equals(str)) {
		return null;
	}
	String [] t = str.split("[\\D]");	
	int max = 0;
	String maxNumStr = null;
	for(String b : t){
		if(null != b && !"".equals(b) && max < b.length()){
			max = b.length();
			maxNumStr = b;
		}			
	}
	return maxNumStr;
}

你可能感兴趣的:(C++,c,C#,J#,idea)