Skip to content
Advertisement

Replacing string for only one time in Java? [closed]

Saying that there are String A = “aabbccdd” and String B = “abcd”, is there any way to remove the matching characters of String B towards String A for only one time?

Expected output is A = “abcd”.

I know it will solve the problem when using for loops, but is there any simpler way to do it? For example, using replaceAll or regular expressions?

Advertisement

Answer

you can use distinct() method

public static void main(String[] args) {
        String str = "aabbccdd";
        String result = str.chars().distinct().boxed()
                .map(c -> (char) (c.intValue()))
                .map(String::valueOf)
                .collect(Collectors.joining());
        System.out.println(result);
    }
Advertisement