java 删除重复字符

时间:2023-01-03 21:44:27
 
/**
 * 删除重复字符
 * @param str 字符串
 * @param deleteStr 删除的字符串
 * @param keepNum 保留字符,从1开始
 * @return
 */
private static String deleteStr(String str,String deleteStr,int keepNum){
keepNum = keepNum - 1;
String deleteStrs = "";
if (deleteStr.equals(".") || deleteStr.equals("|")) {
deleteStrs = "\\"+deleteStr ;
}
String res = "";
String[]  strs=str.split(deleteStrs);
if (keepNum>=strs.length -1) {
keepNum = -1;
}
for(int i=0,len=strs.length;i<len;i++){
System.out.println(strs[i]);
if (i==keepNum) {
  res = res + strs[i].toString()+deleteStr;
}else{
res = res + strs[i].toString();
}
}
return res;
}