I am trying to create a meathod in Java that finds a word (paramter) inside a phrase (parameter) and replace it with another word (parameter). The challenge is to not use any special functions that does the work for me. I would like to know how to find and replace with Java’s built in functions alone (no importing modules). I also cannot use the replace command and would like to change the code with substrings. The code that I currently have is:
public static String searchAndReplace(String phrase, String searchWord, String replaceWord){ String newPhrase = ""; int findIndex = phrase.indexOf(searchWord); while (findIndex >=0){ newPhrase = phrase.substring(0,findIndex)+phrase.substring(findIndex + searchWord.length()); findIndex = phrase.indexOf(replaceWord); } return newPhrase; }
The current code doesn’t work as it is supposed to.
Answer
You were close. Just added replaceWord
in the string concatenation and removed the newPhrase
variable. The final code looks like this:-
public static String searchAndReplace(String phrase, String searchWord, String replaceWord) { int findIndex = phrase.indexOf(searchWord); while (findIndex >= 0) { phrase = phrase.substring(0, findIndex) + replaceWord + phrase.substring(findIndex + searchWord.length()); findIndex = phrase.indexOf(searchWord); } return phrase; }
Edit
The problem with your newPhrase
was at a few places like:-
findIndex = phrase.indexOf(replaceWord); //inside while loop
You changed your newPhrase
but you were still checking for the word in the original phrase
. Also, you were looking for replaceWord
instead of searchWord
.