我正在尝试创建一种方法,该方法可以从字符串中删除所有重复项,或者根据参数仅在一行中保留相同的 2 个字符。
例如:
helllllllo -> helo
或
helllllllo -> hello
- 这保留了双字母
目前我通过执行以下操作删除重复项:
private String removeDuplicates(String word) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < word.length(); i++) {
char letter = word.charAt(i);
if (buffer.length() == 0 && letter != buffer.charAt(buffer.length() - 1)) {
buffer.append(letter);
}
}
return buffer.toString();
}
如果我想保留双字母,我正在考虑使用像 private String removeDuplicates(String word, boolean doubleLetter) 这样的方法
当doubleLetter
为true时,它将返回hello
而不是helo
我不确定在不重复大量代码的情况下执行此操作的最有效方法。
最佳答案
为什么不直接使用正则表达式?
public class RemoveDuplicates {
public static void main(String[] args) {
System.out.println(new RemoveDuplicates().result("hellllo", false)); //helo
System.out.println(new RemoveDuplicates().result("hellllo", true)); //hello
}
public String result(String input, boolean doubleLetter){
String pattern = null;
if(doubleLetter) pattern = "(.)(?=\\1{2})";
else pattern = "(.)(?=\\1)";
return input.replaceAll(pattern, "");
}
}
(.) --> matches any character and puts in group 1.
?= --> this is called a positive lookahead.
?=\\1 --> positive lookahead for the first group
总的来说,这个正则表达式会查找其自身后面的任何字符(正向前瞻)。例如aa或bb等。需要注意的是,实际上只有第一个字符才是匹配的一部分,所以在单词'hello'中,只匹配第一个l((?=\1)部分是< strong>不属于比赛的一部分)。所以第一个 l 被一个空字符串替换,我们剩下 helo,它与正则表达式不匹配
第二个模式是相同的,但是这次我们会预测第一组中的两次出现,例如hello。另一方面,'hello' 将不会被匹配。
在这里查看更多信息:Regex
附注如果有帮助,请自由填写并接受答案。
关于java - 删除一行中重复的相同字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16054321/