Open In App

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

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 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:


Article Tags :