Home > Enterprise >  Remove from string an element of a list or array
Remove from string an element of a list or array

Time:10-16

I have a list or an array of string

String [] elements = {"cat", "dog", "fish"};

and a string

String str = "This is a caterpillar and that is a dogger.";

I want to remove all the items of the array/list from the string if any exists in the string. so that the function should return a string

str = "This is a erpillar and that is a ger." (cat and dog removed from the string)

I can do something like this

private String removeElementsFromString (String str, String [] elements) {
        if(Arrays.stream(elements).anyMatch(str::contains)){
            for(String item : elements){
                str = str.replace(item, "");
            }
        }
        return str;
    }

but what is the elegant way to change the for loop to something else.

CodePudding user response:

Another Solution with StringBuilder :

because it is much faster and consumes less memory.

I think that using StringBuilder instead of String is more appropriate here:

import java.io.IOException;
import java.util.stream.Stream;

public class Bounder {

public static void main(String[] args) throws IOException {
    String[] elements = { "cat", "dog", "fish" };
    String str = "This is a catcatcatcatcatcatcaterpillar ancatcatcatcatd thcatcatcatat is a dogdogdogdogdogdogger.";
// Use StringBuilder here instead of String     
StringBuilder bf = new StringBuilder(str);
    str =null;

    System.out.println("Original String   =  "   bf.toString());
    Stream.of(elements).forEach(e -> {
        int index = bf.indexOf(e);
        while (index != -1) {
            index = bf.indexOf(e);
            if (index != -1) {
                bf.delete(index, index   e.length());
            }
        }
    });

    System.out.println("Result            =  "   bf.toString());
}
}

Output :

  Original String   =  This is a catcatcatcatcatcatcaterpillar ancatcatcatcatd thcatcatcatat is a dogdogdogdogdogdogger.

  Result            =  This is a erpillar and that is a ger.

CodePudding user response:

One-liner solution

The following one-liner does the job:

str = str.replaceAll(Arrays.stream(elements).map(s -> "(?:"   s   ")").collect(Collectors.joining("|")), "");

Demo:

import java.util.Arrays;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        String[] elements = { "cat", "dog", "fish" };
        String str = "This is a caterpillar and that is a dogger.";
        
        str = str.replaceAll(Arrays.stream(elements).map(s -> "(?:"   s   ")").collect(Collectors.joining("|")), "");

        System.out.println(str);
    }
}

Output:

This is a erpillar and that is a ger.

ONLINE DEMO

Explanation:

Arrays.stream(elements).map(s -> "(?:" s ")").collect(Collectors.joining("|")) results into the regex, (?:cat)|(?:dog)|(?:fish) which means cat or dog or fish.

The next step is to replace this resulting regex by "".

CodePudding user response:

I would simply use:

private String removeElementsFromString(String str, String[] elements) {
    for (String item : elements) {
        str = str.replace(item, "");
    }
    return str;
}

I don't see any advantage of the first condition:

if(Arrays.stream(elements).anyMatch(str::contains)) {

CodePudding user response:

The most concise way would be to use replaceAll, which accepts a regular expression as the first parameter:

String newStr = str.replaceAll(String.join("|", elements), "");

This only works because the things in elements have no special regex characters. If any of them did (or there was a chance they did), you'd have to quote them:

String pattern = Arrays.stream(elements).map(Pattern::quote).collect(Collectors.joining("|"));

Note, however, that this would operate in a single pass. So if you had a string like:

docatg

this approach would result in dog, whereas an approach which does input.replace("cat", "").replace("dog", "") would remove the dog as well.

CodePudding user response:

Arrays.stream(elements).reduce(str, (r, w) -> r.replace(w, ""))

with the expected output.

If you want to reduce the input string until it is no longer possible, it is best to iterate until there are no changes

String n = str, o = null;
do {
    n = stream(elements).reduce(o = n, (r, w) -> r.replace(w, ""));
} while(!n.equals(o));

System.out.println(n);

then, with input string

This is a caterpillar and that is a docatg.

you'll get

This is a erpillar and that is a .

CodePudding user response:

You can do it like this. Just use a simple loop.

for (String word : elements) {
            str = str.replace(word,"");
}
  • Related