字符串替换问题
求教!
给出字符串,例如q3t2abc应该替换数字右边的字符变成qttttaaabc.
再如12ra应该替换成1rrra。字符串最后数字不替换。
该是怎样的思路呀?
------解决方案--------------------没有优化,代码如下,希望对你有点帮助
package com.ddpie;
public class TestStr {
public static String parse(String in){
if(in==null || in.trim().length()==0)
return " ";
StringBuffer out = new StringBuffer();
for(int i=0 ; i <in.length()-1 ; i++){
char c1 = in.charAt(i);
int type1 = Character.getType(c1);
char c2 = in.charAt(i+1);
int type2 = Character.getType(c2);
if(type1!=9){//不是数字
out.append(c1);
continue;
}
if(type2==9){//是数字
out.append(c1);
continue;
}
int valueOfC1 = Integer.parseInt(new Character(c1).toString());
for(int j=0 ; j <valueOfC1 ; j++){
out.append(c2);
}
}
out.append(in.charAt(in.length()-1));
return out.toString();
}
public static void main(String[] args){
String str = " ";
// str = "q3t2abc ";
str = "12ra ";
System.out.println(TestStr.parse(str));
}
}
------解决方案--------------------public static String apprendString(String srcString){
if (srcString == null || srcString.trim().length() == 0){
return " ";
}
Pattern pattern = Pattern.compile( "(\\d[a-zA-Z]) ");
Matcher matcher = pattern.matcher(srcString);
int start = 0;
StringBuilder sb = new StringBuilder( " ");
while (matcher.find(start)){
String tmp = matcher.group(1);
int index = srcString.indexOf(tmp,start);
int nextStart = index + tmp.length();
sb.append(srcString.substring(start, index));
int n = Integer.parseInt(Character.toString(tmp.charAt(0)));
for (int i = 0; i <= n; i ++){
sb.append(tmp.charAt(1));
}
start = nextStart;
}
sb.append(srcString.substring(start));
System.out.println(sb.toString());
return sb.toString();
}