Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Kotlin – Replace only last given String from String

I’d like to replace String from another String, but only the last found String. For example:

"ONE, TWO, THREE, FOUR".replaceLast(",", " &") // Outputs: "ONE, TWO, THREE & FOUR"

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

To replace only the last occurrence of a substring in a Kotlin string, you can use an extension function. Here’s a Kotlin extension function that accomplishes this:

Kotlin:

fun String.replaceLast(oldValue: String, newValue: String): String {
    val lastIndex = lastIndexOf(oldValue)
    if (lastIndex == -1) {
        return this
    }
    val prefix = substring(0, lastIndex)
    val suffix = substring(lastIndex + oldValue.length)
    return "$prefix$newValue$suffix"
}

fun main() {
    val input = "ONE, TWO, THREE, FOUR"
    val result = input.replaceLast(",", " &")
    println(result) // Output: "ONE, TWO, THREE & FOUR"
}

Java:

public class Main {
    public static String replaceLast(String input, String oldValue, String newValue) {
        int lastIndex = input.lastIndexOf(oldValue);
        if (lastIndex == -1) {
            return input;
        }
        String prefix = input.substring(0, lastIndex);
        String suffix = input.substring(lastIndex + oldValue.length());
        return prefix + newValue + suffix;
    }

    public static void main(String[] args) {
        String input = "ONE, TWO, THREE, FOUR";
        String result = replaceLast(input, ",", " &");
        System.out.println(result); // Output: "ONE, TWO, THREE & FOUR"
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading