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

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

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);
}


第三版: :idea:

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值