Open In App

How to Replace the Last Occurrence of a Substring in a String in Java?

Last Updated : 29 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn about replacing the last instance of a certain substring inside a string as a typical need. We’ll look at a practical Java solution for this in this post.

Replace the last occurrence of a Substring in a String in Java

We may use the lastIndexOf() method to determine the location of the last occurrence of a substring in a Java string, and then we can use the substring() method to build a new string with the replacement. The substrings that come before and after the target substring are then concatenated.

An example of the above-mentioned topic is given below:

Java




// Java Program Replace the last
// Occurrence of a Substring in a String
  
// Driver Class
public class ReplaceLastOccurrenceExample {
    public static String replaceLastOccurrence(String original, String target, String replacement) {
        int lastIndex = original.lastIndexOf(target);
  
        if (lastIndex == -1) {
            // Target substring not found
            return original;
        }
  
        String before = original.substring(0, lastIndex);
        String after = original.substring(lastIndex + target.length());
  
        return before + replacement + after;
    }
  
      // Main Function
    public static void main(String[] args) {
        String inputString = "Hello world, how's the world today?";
        String targetSubstring = "world";
        String replacementSubstring = "universe";
  
        String result = replaceLastOccurrence(inputString, targetSubstring, replacementSubstring);
  
        System.out.println("Original String: " + inputString);
        System.out.println("String after replacement: " + result);
    }
}


Output

Original String: Hello world, how's the world today?
String after replacement: Hello world, how's the universe today?



Explanation of the above Program:

  • Three arguments are required for the replaceLastOccurrence method: the original string, the target substring that has to be changed, and the replacement substring.
  • To determine the location of the target substring’s last occurrence, it uses lastIndexOf().
  • The original text is returned unaltered if the desired substring cannot be located (lastIndex is -1).
  • substring() is then used to extract the substrings that come before and after the target substring.
  • In order to create the updated string, it concatenates these substrings with the replacement substring.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads