Check if a string contains another string twice

Mad Scientist :

I have a for loop which iterates through a maplist and now I want to check every entry of the maplist if it contains a certain String more than once and then delete all Strings except the first one which occurs but I have no clue how to do it.

for (Map<String, String> entry : mapList) {
    String line = "";
    for (String key : entry.keySet()) {
        if (StringUtils.containsAny(key, "5799"){
            line += entry.get(key) + "|";
        }
        list1.add(line);
    }
}

I am thankful for every idea.

Andreas :

To see if key contains a string s at least twice, and to remove the second occurrence, use indexOf twice, with the second call starting the search after the first occurrence:

static String removeSecond(String key, String s) {
    int idxFirst = key.indexOf(s);
    if (idxFirst != -1) {
        int idxSecond = key.indexOf(s, idxFirst + s.length());
        if (idxSecond != -1) {
            return key.substring(0, idxSecond) +
                   key.substring(idxSecond + s.length());
        }
    }
    return key; // Nothing to remove
}

Test

System.out.println(removeSecond("mississippi", "ss")); // prints: missiippi
System.out.println(removeSecond("mississippi", "i"));  // prints: missssippi
System.out.println(removeSecond("mississippi", "pp")); // prints: mississippi

UPDATE

If you want to remove all duplicates, i.e. leave only the first occurrence, keep searching. For best performance of building the new string, use StringBuilder.

static String removeDuplicates(String key, String s) {
    int idx = key.indexOf(s);
    if (idx == -1)
        return key; // Nothing to remove
    StringBuilder buf = new StringBuilder();
    int prev = 0;
    for (int start = idx + s.length(); (idx = key.indexOf(s, start)) != -1; prev = start = idx + s.length())
        buf.append(key.substring(prev, idx));
    return (prev == 0 ? key : buf.append(key.substring(prev)).toString());
}

Test

System.out.println(removeDuplicates("mississippi", "ss")); // prints: missiippi
System.out.println(removeDuplicates("mississippi", "i"));  // prints: misssspp
System.out.println(removeDuplicates("mississippi", "s"));  // prints: misiippi
System.out.println(removeDuplicates("mississippi", "ab")); // prints: mississippi

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=327249&siteId=1