public class RegExprTest { public static void main(String[] args) { String a = "abcccccci!ppppc"; a = a.replaceAll("([a-z!])\\1+", "$1"); System.out.println(a); } }
重新写了一个,要进行多次替换才能做到。public class PatternTest { public static void main(String[] args) { String a = "abdcdddddcaaaeaaecdeafeaccefa"; // 这一句可以减少循环的次数 // 这一句也可以改为 tmp = a.replaceAll("(.)(.*)\\1", "$1$2"); // 这样会增加循环的次数 String tmp = a.replaceAll("(.)\\1+", "$1"); int k = 0; while(!a.equals(tmp)) { a = tmp; tmp = a.replaceAll("(.)(.*)\\1", "$1$2"); k++; } System.out.println(a); System.out.println(k); } }为了将 abdcdddddcaaaeaaecdeafeaccefa 变为 abdcef 需要进行 11 次替换操作!我实在想不出其他的办法了。
无解 这种字符:String a = "abcdefghijklmnmnmnmnmnm";交叉重复是无法过滤的
import java.util.*;public class Filter { public static void main(String[] args) { String a = "abcccccci!ppppc"; Set<String> s = new HashSet<String>(); StringBuffer buf = new StringBuffer(); for (int i=0; i<a.length();i++) { String c = a.substring(i,i+1); if (s.contains(c)) { continue; } s.add(c); buf.append(c); } System.out.println(buf); } }
不如 循环charAt(i) {然后判断后面的是否连续 等于charAt(i) }
public static void main(String[] args) {
String a = "abcccccci!ppppc";
a = a.replaceAll("([a-z!])\\1+", "$1");
System.out.println(a);
}
}
String a = "abcccccci!ppppc";
过滤后应该为:abci!p
----------------------
不对吧,过滤后应该是:abci!pc <--- 你漏了一个“c” o(∩_∩)o
public static void main(String[] args) {
String a = "abcccccci!ppppc";
a = a.replaceAll("(.)\\1+", "$1");
System.out.println(a);
}
}
String a = "abcccccci!ppppc ";
过滤后应该为:abci!p
----------------------
不对吧,过滤后应该是:abci!pc <--- 你漏了一个“c” o(∩_∩)o_______________________________________________________
就是要过滤后面的那个"c"啊.
public static void main(String[] args) {
String a = "abdcdddddcaaaeaaecdeafeaccefa";
// 这一句可以减少循环的次数
// 这一句也可以改为 tmp = a.replaceAll("(.)(.*)\\1", "$1$2");
// 这样会增加循环的次数
String tmp = a.replaceAll("(.)\\1+", "$1");
int k = 0;
while(!a.equals(tmp)) {
a = tmp;
tmp = a.replaceAll("(.)(.*)\\1", "$1$2");
k++;
}
System.out.println(a);
System.out.println(k);
}
}为了将 abdcdddddcaaaeaaecdeafeaccefa 变为 abdcef 需要进行 11 次替换操作!我实在想不出其他的办法了。
这种字符:String a = "abcdefghijklmnmnmnmnmnm";交叉重复是无法过滤的
{
public static void main(String[] args)
{
String a = "abcccccci!ppppc";
Set<String> s = new HashSet<String>();
StringBuffer buf = new StringBuffer();
for (int i=0; i<a.length();i++) {
String c = a.substring(i,i+1);
if (s.contains(c)) {
continue;
}
s.add(c);
buf.append(c);
}
System.out.println(buf);
}
}
//改了一下火龙果的代码,可以了
public class TruncateSameStringWithRegex { public static void main(String[] args) throws Exception {
String str = "ab890f4f";
str = truncateString(str);
System.out.println(str);
} private static String truncateString(String str) {
// 这一句可以减少循环的次数
// 这一句也可以改为 tmp = a.replaceAll("(.)(.*)\\1", "$1$2");
// 这样会增加循环的次数
String tmp = str.replaceAll("(.)\\1+", "$1");
str = str +" ";
int k = 0;
while (!str.equals(tmp)) {
str = tmp;
tmp = str.replaceAll("(.)(.*)\\1", "$1$2");
k++;
}
return str.substring(0,str.length());
}}