Java Replace nth Occurrence String

Java Replace nth Occurrence String | Java provides several methods to replace a string. In this problem we have to replace the nth occurance of a string in the given string.

Let us first understand the problem with some example and then we will see the solution part. An example of Java Replace nth Occurrence String:-

String = “good morning, good afternoon, good evening goodnight”;
String to be replaced = “good”
String to place = “bad”
Occurance = 3

In the given string we want to replace the 3rd occurance of “good” string with the “bad” string. After replacement the resultant string will be as below.

Resultant String = “good morning, good afternoon, bad evening goodnight”;

To solve this problem (Java Replace nth Occurrence String) we have to perform the following tasks:-
1) First find the index where string occurs nth time.
2) Replace the string at the given index.

Java Replace nth Occurrence String

import java.util.Scanner;

public class Main {

   public static void main(String[] args) {
      Scanner scan = new Scanner(System.in);

      System.out.print("Enter String: ");
      String string = scan.nextLine();
      System.out.print("String to be replaced: ");
      String strToReplace = scan.nextLine();
      System.out.print("New string to place: ");
      String newStr = scan.nextLine();
      System.out.print("Occurance: ");
      int occurance = scan.nextInt();

      String replacedString = 
         replaceNthOccurance(string, strToReplace, newStr, occurance);

      System.out.println("Resultant String: " + replacedString);
      scan.close();
   }

   public static String replaceNthOccurance(String string, 
                 String strToReplace, String newStr, int occurance) {

      int index = indexOfNthOccurrence(string, strToReplace, occurance);
      if (index == -1) {
         System.out.println("\"" + strToReplace + "\" not found " + 
                           occurance + " times in the given string");
         return string;
      }

      return string.substring(0, index) + newStr + 
            string.substring(index + strToReplace.length());
   }

   private static int indexOfNthOccurrence(String string, 
                                    String strToReplace, int n) {
      String tempStr = string;
      int tempIndex = -1;
      int finalIndex = 0;

      for (int occurrence = 0; occurrence < n; ++occurrence) {
         tempIndex = tempStr.indexOf(strToReplace);
         if (tempIndex == -1) {
            finalIndex = 0;
            break;
         }

         tempStr = tempStr.substring(++tempIndex);
         finalIndex += tempIndex;
      }

      return --finalIndex;
   }
}

Output:-

Enter String: good morning, good afternoon, good evening goodnight
String to be replaced: good
New string to place: Hello
Occurance: 3
Resultant String: good morning, good afternoon, Hello evening goodnight

Test-case when the string doesn’t occur in the given string.

Enter String: good morning, good afternoon, good evening goodnight
String to be replaced: Hello
New string to place: Hi
Occurance: 2
“Hello” not found 2 times in the given string
Resultant String: good morning, good afternoon, good evening goodnight

Test-case when the string occur in the given string but the occurance values is greater than the actual occurance.

Enter String: good morning, good afternoon, good evening goodnight
String to be replaced: good
New string to place: Hi
Occurance: 9
“good” not found 9 times in the given string
Resultant String: good morning, good afternoon, good evening goodnight

Test-case when the string occur in the given string but the occurance values is invalid i.e. negative or zero.

Enter String: good morning, good afternoon, good evening goodnight
String to be replaced: good
New string to place: Hi
Occurance: -5
“good” not found -5 times in the given string
Resultant String: good morning, good afternoon, good evening goodnight

In the above example we have used substring() and indexOf() method of the Java String class. The substring() method of the String class is used to find the substring of the given string based on the index. And the indexOf() method is used to find the index of a string in the given string. If a string doesn’t occur in the given string then indexOf() method returns -1.

To replace nth Occurrence String we have developed 2 methods in the above example:- replaceNthOccurance() and indexOfNthOccurrence(). To replace the nth occurance string first we need to find the index where string occured nth times.

The indexOfNthOccurrence() method find the index of string in the given string and it returns -1 in the following cases:-

  • If occurance value is invalid i.e. negative or 0.
  • If string doesn’t occur in the given string.
  • If string exist but doesn’t occur the given occurance times.

The replaceNthOccurance() method first calls the indexOfNthOccurrence() to find the index position. If the return value is -1 then it display appriorate message that string doesn’t exist the given number of times, and return the original string. Otherwise substring() method is called to replace the string. Finally resultant string is returned to the caller method.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published.