如何从Java中的另一个字符串中删除字符串的重复项?

时间:2016-10-18 20:20:37

标签: java arrays regex string

所以我需要从Java中的另一个字符串中删除特定字符串的重复项,例如:

'test12312312312'       -> Remove duplicates of '123', output -> 'test12312'
'my sentence-!!!!!!!!!' -> Remove duplicates of '!!' , output -> 'my sentence-!!!'
'3rd ?!?!?!abd%3!?!?!??'-> Remove duplicates of '!?' , output -> '3rd ?!?!abd%3?'

希望这些例子清楚地表明这一点。例如你传递一个函数任意两个字符串,它从第二个字符串中删除第一个的所有重复项。例如,它可能看起来像:

String removeDuplicates(String checkString, String message) {
    //Return 'message' with duplicates of 'checkString' removed
}

我已经看到了各种各样的实现,用于删除字符串的所有实例,或删除特定字符的重复项 - 但没有一个实现字符串的第一次出现。有什么想法吗?

4 个答案:

答案 0 :(得分:1)

使用String#replace

String needle = /* search string */;
String base = /* input string */;
int firstLoc = base.indexOf(needle);
if (firstLoc > 0) {
    int cutoff = firstLoc + needle.length();
    return base.substring(0, cutoff) + base.substring(cutoff).replace(needle, "");
}
return base;

除此之外,您可以遍历字符串,如果搜索字符串的第一个字符与您当前的字符匹配,请查看余数是否构成字符串总数。如果确实如此,那么就跳过去。您基本上只是重建字符串:

//Precondition: needle not empty, vars not null, etc
StringBuilder back = new StringBuilder();
String needle = /* search string */;
String base = /* input string */;
boolean first = true;
for (int i = 0; i < base.length(); i++) {
    char c = base.charAt(i);
    if (c == needle.charAt(0)
          && base.substring(i, Math.min(base.length(), i + needle.length())).equals(needle)) {
        if (first) {
            first = false;
        } else {
            i += needle.length() - 1;
            continue;
        }
    }
    back.append(c);
}
return back.toString();

答案 1 :(得分:1)

这是一个实现,它为您提供更新示例中的输出。

private static String removeDuplicates(String checkString, String message) {
    int idx = message.indexOf(checkString); // Find first occurrence of checkString
    if (idx == -1)
        return message; // No occurrence of checkString found
    idx += checkString.length(); // Skip first occurrence of checkString
    StringBuilder buf = new StringBuilder(message);
    while ((idx = buf.indexOf(checkString, idx)) != -1)
        buf.delete(idx, idx + checkString.length());
    return buf.toString();
}

这不是最好的最佳方式,但这是一个相当简单的解决方案。

测试

System.out.println(removeDuplicates("123", "test12312312312"));
System.out.println(removeDuplicates("!!", "my sentence-!!!!!!!!!"));
System.out.println(removeDuplicates("!?", "3rd ?!?!?!abd%3!?!?!??"));

输出

test12312
my sentence-!!!
3rd ?!?!abd%3?

答案 2 :(得分:0)

String removeDuplicates(String checkString, String message) {
    return checkString.replaceAll("("+message+")+", message);
}

这会在message链中留下一个message。 这只有在彼此紧接着的情况下才有效。

答案 3 :(得分:0)

我看到两种方式:

  1. 查找子串的第一次出现。如果没有出现,则返回输入字符串。如果出现这种情况,请将所有内容保存到该点(连同出现的那样),在输入字符串中进一步删除所有出现的内容。

  2. 在重复的字符串上拆分输入文本。返回结果[0] +重复+ rest.join(&#34;&#34;)

  3. 不确定哪种方式会更快。