Java – Replace Last Occurrence of a String

The below code example shows you the way to replace the last occurrence of a string in Java.

StringExample.java
package com.bytenota;

public class StringExample {
    
    public static String replaceLast(String find, String replace, String string) {
        int lastIndex = string.lastIndexOf(find);
        
        if (lastIndex == -1) {
            return string;
        }
        
        String beginString = string.substring(0, lastIndex);
        String endString = string.substring(lastIndex + find.length());
        
        return beginString + replace + endString;
    }
    
    public static void main(String[] args) {
        String str1 = "Hello World-";
        String newStr1 = replaceLast("-", "", str1);
        System.out.println(newStr1); // Hello World
        
        String str2 = "Foo and Bar. Hello Bar";
        String newStr2 = replaceLast("Bar", "guys", str2);
        System.out.println(newStr2); // Foo and Bar. Hello guys
    }
    
}

Output:

Hello World
Hello World. Hi you guys.

0 0 vote
Article Rating
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Anirudh
Anirudh
2 years ago

Works great!

1
0
Would love your thoughts, please comment.x
()
x