public void print(){ System.out.println("matcher: "+matcher); } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Match m = new Match("abcd1243","azzz12"); m.match(); m.print();
m = new Match("sdfsdg123jhg","yuop123z"); m.match(); m.print(); }}
public class Match {
private String source1;
private String source2;
private ArrayList<String>matcher;
public Match(String source1,String source2){
this.source1 = source1;
this.source2 = source2;
matcher = new ArrayList<String>();
}
public void match(){
String longer;
String shorter;
if(source1.length()>=source2.length()){
longer = source1;
shorter = source2;
}
else{
longer = source2;
shorter = source1;
}
for(int i=shorter.length(); i>0; i--){
for(int j=0; j+i<=shorter.length(); j++){
String tmp = shorter.substring(j,j+i);
if(longer.indexOf(tmp)>=0){
matcher.add(tmp);
shorter = shorter.replace(tmp,"");
break;
}
}
}
}
public void print(){
System.out.println("matcher: "+matcher);
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Match m = new Match("abcd1243","azzz12");
m.match();
m.print();
m = new Match("sdfsdg123jhg","yuop123z");
m.match();
m.print();
}}
shorter = shorter.replace(tmp,"");
改成
shorter = shorter.replaceAll(tmp,"");因为replace只能替换字符,而replace可以替换字符串.改动后运行无误,,
改成
shorter = shorter.replaceAll(tmp,"");因为replace只能替换字符,而replace可以替换字符串.改动后运行无误,,
--------------------------
看jdk1.5的javadoc,你就知道不改也可以