How to replace last character in String when it is in an Array

Viewed 2085

If some String ends with a character that is in arrayOf(X, Y, Z) I want to replace it with new char A. I don't know how to do this, and everything I've tried doesn't work.

3 Answers

You can do this like this:

var test = "Some string Z"

if (test.lastOrNull() in arrayOf('X', 'Y', 'Z')) //check if the last char == 'X' || 'Y' || 'Z'
{
    test = test.dropLast(1) + 'A' // if yes replace with `A`
}

println(test) // "Some string A"

Or with using extension function:

fun String.replaceLast(toReplace: CharArray, newChar: Char): String
{
    if (last() in toReplace)
    {
        return dropLast(1) + 'A'
    }
    return this
}

//Test
val oldTest = "Some string Z"
val newTest = oldTest.replaceLast(charArrayOf('X', 'Y', 'Z'), 'A')

println(newTest) // "Some string A"

Simply use this regexp:

val regEx = "[XYZ]$".toRegex()
val result = initialString.replace(regexp,"A")

$ in regex means last character of a string

You can use a combination of lastIndexOf and dropLast functions of String class:

private fun replaceLastChar(original: String, replacement: Char = 'A'): String {
    if (original.lastIndexOf('Z')
        + original.lastIndexOf('X')
        + original.lastIndexOf('Y') > 0
    ) {
        return original.dropLast(1) + replacement
    }
    return original
}
Related