Finding, removing, and replacing a words in a string (manually) Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Finding, removing, and replacing a words in a string (manually) without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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.

We are here to answer your question about Finding, removing, and replacing a words in a string (manually) - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji