user3420034 user3420034 - 1 year ago 58
Java Question

How to remove duplicates of a string from another string in Java?

So I need to remove duplicates of a specific string from another string in Java, a few examples:

'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?'

Hopefully those examples make this clear. e.g. you pass a function any two strings, and it removes all duplicates of the first one from the second. For example it might look like:

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

I've seen various implementations of this for removing all instances of the string, or removing duplicates of a specific character - but none that keep the first occurance of a string. Any ideas?

Answer Source

Here is an implementation that gives you the output in the updated examples.

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();

It's not the most optimal way of doing it, but it is a fairly simple solution.


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


my sentence-!!!
3rd ?!?!abd%3?
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download