简体   繁体   中英

Remove elements from String array using another String array Java

I am trying to remove elements from String A using an array of String B. My logic is to convert the string A to an array and then check if A contains the same elements as B and write that data to an empty String, but it doesn't work if B has two or more elements. Can you tell me what I'm doing wrong?

class Test {
    public static void main(String[] args) {
        WordDeleter wordDeleter = new WordDeleter();

        // Hello
        System.out.println(wordDeleter.remove("Hello Java", new String[] { "Java" }));

        // The Athens in
        System.out.println(wordDeleter.remove("The Athens is in Greece", new String[] { "is", "Greece" }));

        // This cat
        System.out.println(wordDeleter.remove("This is cat", new String[] { "is" }));
    }
}

class WordDeleter {
    public String remove(String phrase, String[] words) {       
        String[] arrayPhrase = phrase.split(" ");       
        String result = "";
        
        for (int i = 0; i < arrayPhrase.length; i++) {
            for (int j = 0; j < words.length; j++) {
                if (!arrayPhrase[i].equalsIgnoreCase(words[j]))
                    result += arrayPhrase[i] + " ";
            }
        }
        return result.trim();
    }
}

Output is:

Hello
The The Athens Athens is in in Greece
This cat

You're close but you need to use the helpful .contains() method. This should work for the multi-length set of words. Your nested for loop checked for both words, thus the copying. Also the not-allowed words were only written once, so it infact "worked" but not the way you intended.

class Test {
    public static void main(String[] args) {
        WordDeleter wordDeleter = new WordDeleter();

        // Hello
        System.out.println(wordDeleter.remove("Hello Java", new String[] { "Java" }));

        // The Athens in
        System.out.println(wordDeleter.remove("The Athens is in Greece", new String[] { "is", "Greece" }));

        // This cat
        System.out.println(wordDeleter.remove("This is cat", new String[] { "is" }));
    }
}

class WordDeleter {
    public String remove(String phrase, String[] words) {       
        String[] arrayPhrase = phrase.split(" ");       
        String result = "";
        
        for (int i = 0; i < arrayPhrase.length; i++) {
            // If the word is not contained in the not allowed array
            if(!words.contains(arrayPhrase[i])){
                       result += arrayPhrase[i] + " ";
            }
        }
        return result.trim();
    }
}

Another thing you can do to make it better is use StringBuilder . Instead of String result = "" , use StringBuilder result = new StringBuilder() . And instead of result +=arrayPhrase[i] + " "; use result.append(arrayPhrase[i] + " "); as so:

class Test {
    public static void main(String[] args) {
        WordDeleter wordDeleter = new WordDeleter();

        // Hello
        System.out.println(wordDeleter.remove("Hello Java", new String[] { "Java" }));

        // The Athens in
        System.out.println(wordDeleter.remove("The Athens is in Greece", new String[] { "is", "Greece" }));

        // This cat
        System.out.println(wordDeleter.remove("This is cat", new String[] { "is" }));
    }
}

class WordDeleter {
    public String remove(String phrase, String[] words) {       
        String[] arrayPhrase = phrase.split(" ");       
        StringBuilder result = new StringBuilder();
        
        for (int i = 0; i < arrayPhrase.length; i++) {
            // If the word is not contained in the not allowed array
            if(!words.contains(arrayPhrase[i])){
                      result.append(arrayPhrase[i] + " ");
            }
        }
        return result.toString().trim();
    }
}

The most efficient way to remove all occurrences of strings contained in the given array from the given string is to generate a HashSet from the given array and check for every word in the given string , whether it's present in the set or not.

To avoid overheads of string concatenation, we can use StringJoiner .

That's how it can be implemented.

public static String remove(String phrase, String[] words) {
    String[] arrayPhrase = phrase.split(" ");
    Set<String> wordsToRemove = Arrays.stream(words).collect(Collectors.toSet());
    StringJoiner result = new StringJoiner(" ");
    
    for (String word: arrayPhrase) {
        if (!wordsToRemove.contains(word)) {
            result.add(word);
        }
    }
    
    return result.toString();
}

And that's how it can be implemented with streams using collector joining() :

public static String remove(String phrase, String[] words) {
    
    Set<String> wordsToRemove = Arrays.stream(words).collect(Collectors.toSet());
    
    return Arrays.stream(phrase.split(" "))
        .filter(word -> !wordsToRemove.contains(word))
        .collect(Collectors.joining(" "));
}

A link to Online Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM