Hex*_*y21 6 android kotlin android-studio
如果某个字符串以 in 中的字符结尾,arrayOf(X, Y, Z)我想将其替换为 new char A。我不知道该怎么做,我尝试过的一切都不起作用。
你可以这样做:
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)
| 归档时间: |
|
| 查看次数: |
4781 次 |
| 最近记录: |