当字符串在数组中时,如何替换字符串中的最后一个字符 [英] How to replace last character in String when it is in an Array

查看:112
本文介绍了当字符串在数组中时,如何替换字符串中的最后一个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果某些String以arrayOf(X, Y, Z)中的字符结尾,我想用新的char A替换它.我不知道该怎么做,而且我尝试过的所有方法都不起作用.

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.

推荐答案

您可以这样做:

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"

这篇关于当字符串在数组中时,如何替换字符串中的最后一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆