替换字符串中连续出现的指定字符串

来源:互联网 发布:哈佛法学院 知乎 编辑:程序博客网 时间:2024/04/29 01:05

本题来自《程序员代码面试指南》(左程云)著

题目:给定三个字符串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--;        }    }    }


0 0
原创粉丝点击