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
if(certainWord in stringA and certainWord in stringB), remove from stringB?contains()or any other method on the array instance.words.contains()would not even compile.