获取字符串的公共字母,比如abcse和ewefa,则公共部分是ea
代码如下,代码算法不是最优,灵活度上尚可
import java.util.HashMap;
import java.util.Iterator;
public class StringCmp {
private HashMap<String,Integer> map = new HashMap();
private int count = 0;//需要比较的字符串
private boolean ignoreCap = false;//忽略大小写 danielinbiti
private HashMap tmpMap = new HashMap();//过来一个字符串中重复的字符 danielinbiti
public StringCmp(){
this(false);
}
public StringCmp(boolean ignoreCap){
map.clear();
this.count = 0;
this.ignoreCap = ignoreCap;
}
public void putMap(String tsub){
if(this.ignoreCap){
tsub = tsub.toLowerCase();
}
if(tmpMap.get(tsub)==null){
tmpMap.put(tsub, 1);
Integer num = map.get(tsub);
if(num==null){
map.put(tsub+"", 1);
}else{
map.put(tsub+"",++num);
}
}
}
public void addString(String str){
char tsub;
tmpMap.clear();
if(str!=null&&str.trim().length()>0){
this.count++;
for(int i=0;i<str.length();i++){
tsub = str.charAt(i);
this.putMap(tsub+"");
}
}
}
public String getISTion(){
StringBuffer s = new StringBuffer();
Iterator iter = map.keySet().iterator();
while(iter.hasNext()){
String key = (String)iter.next();
if(map.get(key)==this.count){
s.append(key);
}
}
return s.toString();
}
public static void main(String[] args) {
StringCmp sc = new StringCmp(false);
sc.addString("Marginle");
sc.addString("Valaienie");
sc.addString("mdsA");
System.out.println(sc.getISTion());
}
}