本题来自《程序员代码面试指南》(左程云)著
题目:给定三个字符串str,from,to,已知from字符串中无重复字符,把str中所有的from字符串替换为to字符串,然后替换后的字符串。
举例:str="123abc",from="abc",to="456",return "123456";
import java.io.*;
class test
{
public static void main (String[] args) throws java.lang.Exception
{
String aa="sfsf3hkj435-434kjfd--535sdfgs";
String result=replace(aa,"435","aaaaaaaaaaaaaaa");
System.out.println(result);
}
public static String replace(String str,String from,String to){
if(str==null||str.equals("")||from==null||from.equals("")){
return str;
}
char[] strArr=str.toCharArray();
char[] fromArr=from.toCharArray();
int match=0;
for(int i=0;i<strArr.length;i++){
if(strArr[i]==fromArr[match]){
match++;
if(match==fromArr.length){
clear(strArr,i,fromArr.length);
match=0;
}
}else{
match=0;
}
}
String result="";
String cur="";
for(int i=0;i<strArr.length;i++){
if(strArr[i]!=0){
cur=cur+String.valueOf(strArr[i]);
}
if(strArr[i]==0&&(i==0||strArr[i-1]!=0)){
result=result+cur+to;
cur="";
}
}
if(!cur.equals("")){
result=result+cur;
}
return result;
}
public static void clear(char[] str,int end ,int length){
while(length!=0){
str[end]=0;
end--;
length--;
}
}
}