0

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
4
  • When you say remove elements, you mean that if(certainWord in stringA and certainWord in stringB), remove from stringB? Commented Jul 19, 2022 at 14:47
  • This means I need to collect the data from Sting A without the words from String B, hope you understand @BenjaminW. Commented Jul 19, 2022 at 14:49
  • The result should be \\Hello, \\The Athens in, \\This cat @BenjaminW. Commented Jul 19, 2022 at 14:51
  • 1
    Mind that arrays have no behavior in Java, it's impossible to invoke contains() or any other method on the array instance. words.contains() would not even compile. Commented Jul 19, 2022 at 16:41

2 Answers 2

2

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[] wordsArray) {       
        List<String> words = Arrays.asList(wordsArray);
        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();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.