当字符串位于数组中时,如何替换字符串中的最后一个字符

Hex*_*y21 6 android kotlin android-studio

如果某个字符串以 in 中的字符结尾,arrayOf(X, Y, Z)我想将其替换为 new char A。我不知道该怎么做,我尝试过的一切都不起作用。

ikn*_*now 4

你可以这样做:

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"
Run Code Online (Sandbox Code Playgroud)

或者使用扩展函数:

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"
Run Code Online (Sandbox Code Playgroud)

  • 您可以使用“dropLast(1)”代替“substring(0, test.length - 1)” (2认同)