62,621
社区成员
发帖
与我相关
我的任务
分享package com.saturday;
public class KMP {
public static String myReplaceAll(
String input,
String replaced){
//短路掉不可能匹配的情况
if(replaced.equals("")
||input.length()<replaced.length()){
return input;
}
StringBuffer buf=new StringBuffer();
char[] s=input.toCharArray();
char[] r=replaced.toCharArray();
int rLen=r.length;
int matchCount;
for(int i=0,sLen=s.length;i<sLen;){
if(i<sLen-rLen){
//检查匹配
matchCount=0;
for(int j=0;j<rLen;j++){
if(s[i+j]==r[j]){
matchCount++;
}else{
break;
}
}
//完全匹配
if(matchCount==rLen){
i+=rLen;
continue;
}
//部分匹配
if(matchCount>0){
for(int j=0;j<matchCount;j++){
buf.append(s[i++]);
}
continue;
}
}
buf.append(s[i++]);
}
return buf.toString();
}
public static void main(String[] args){
String input="123 mfc mf fc mfdC mfmfc cmfc dd abc";
String replaced="1234";
System.out.println(
myReplaceAll(input,replaced).equals(input.replaceAll(replaced,""))
);
}
}
package test;
public class Myreplace {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Myreplace.myReplaceAll("abcdefghhhhcedcdehabchhhh", "cde","!");
}
public static String myReplaceAll(String input,String regx,String rep)
{
// 特殊情况判断
char i [] = input.toCharArray();
char r [] = regx.toCharArray();
StringBuffer buf = new StringBuffer();
boolean b = false;
for(int k=0;k<i.length;k++)
{
if(i.length-r.length>0)
{
for(int j=0;j<r.length;j++)
{
System.out.println(i[k+j]+"是否匹配"+r[j]);
if(i[k+j]==r[j])
{
b=true;
}
else
{
b=false;
break;
}
}
}
if(b)
{
k+=regx.length()-1;
buf.append(rep);
}else
{
buf.append(i[k]);
}
}
System.out.println(input);
System.out.println(buf);
System.out.println(input.replace(regx, rep));
return input;
}
}