源程序:
public class MyClass1 {
public MyClass1() {
}
/**
* 使用replaceString替换targetString中的matchString
* @param targetString 源字符串
* @param matchString 匹配子串
* @param replaceString 替换字符串
* @return 处理后的源字符串
*/
public final static String replaceString( String target,
String match,
String replace)
{
int first=target.indexOf(match);
/*
System.out.println("fi="+first);
System.out.println("li="+last);
System.out.println("tL="+targetLength);
*/
String replacedString=new String("");;//结果存放在这个变量中
while(first!=-1){
int last=first+match.length();
int targetLength=target.length();
replacedString=target.substring(0,first);
replacedString=replacedString.concat(replace);
target=replacedString.concat(target.substring(last,targetLength));
first = target.indexOf(match);
}
return replacedString;
}
public static void main(String argv[])
{
String s=new String("0783456789");
String m=new String("7");
String r=new String("ab");
System.out.println(s);
System.out.println(m+"->"+r);
s=replaceString(s,m,r);
System.out.println(s);
}
}
最后结果是0ab83456ab 请问各位高手,最后两个89怎么没有啊? 问题出在哪了?
public class MyClass1 {
public MyClass1() {
}
/**
* 使用replaceString替换targetString中的matchString
* @param targetString 源字符串
* @param matchString 匹配子串
* @param replaceString 替换字符串
* @return 处理后的源字符串
*/
public final static String replaceString( String target,
String match,
String replace)
{
int first=target.indexOf(match);
/*
System.out.println("fi="+first);
System.out.println("li="+last);
System.out.println("tL="+targetLength);
*/
String replacedString=new String("");;//结果存放在这个变量中
while(first!=-1){
int last=first+match.length();
int targetLength=target.length();
replacedString=target.substring(0,first);
replacedString=replacedString.concat(replace);
target=replacedString.concat(target.substring(last,targetLength));
first = target.indexOf(match);
}
return replacedString;
}
public static void main(String argv[])
{
String s=new String("0783456789");
String m=new String("7");
String r=new String("ab");
System.out.println(s);
System.out.println(m+"->"+r);
s=replaceString(s,m,r);
System.out.println(s);
}
}
最后结果是0ab83456ab 请问各位高手,最后两个89怎么没有啊? 问题出在哪了?
三行代码搞定了String a="0783456789";
String b=a.replaceAll("7", "ab");
System.out.println(b);