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

//替换字符串中连续出现的指定字符串
public class ReplaceString{
	
	//替换指定的字符串(from 字符串替换成to字符串)
	public static String replaceString(String str,String from,String to)
	{
		if(str==null||from==null||str.equals("")||from.equals(""))
		{
			return str;
		}
		//字符串转数组
		char[]chs=str.toCharArray();
		char[]chf=from.toCharArray();
        
        int match=0; //匹配到的字符串
        //from字符串的替换成0(Null)
		for(int i=0;i<chs.length;i++)
		{
			if(chs[i]==chf[match++])
			{
				if(match==chf.length)
				{  
					//将所有的from串转换成0(此处代码写错)
					clear(chs,i,chf.length);
					match=0;
				}
				
			}else
			{
			  if(chs[i]==chf[0])
			  {
			  	i--;
			  }
			  match=0;
			}
		}
        
        //将连续的0替换成to字符串
        String res="";
        String cur="";
        for(int i=0;i<chs.length;i++)
        {
        	if(chs[i]!=0)
        	{
        		cur=cur+String.valueOf(chs[i]);
        		//System.out.println(cur);
        	}
        	if(chs[i]==0&&(i==0||chs[i-1]!=0))
        	{
        		res=res+cur+to;
        		cur="";
        	}
        }
        if(!cur.equals(""))
        {
        	res=res+cur;
        }

        return res;

	}
     

    //清除from字符串
    public static void clear(char[]ch,int end,int len)
    {
    	while(len--!=0)
    	{
    		ch[end--]=0; //设置为0(转为字符串为null)
    	}

    }

	public static void main(String[]args)
	{
		String str="123abc";
		String from="abc";
		String to="X";
		//字符串替换
		System.out.println(replaceString(str,from,to));


	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值