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"
9 Comments
Stachu
instead of
substring(0, test.length - 1) you can use dropLast(1)Hexley21
first one is better. Thank you!
iknow
@Stachu It looks better with
dropLast(1), I edited my answer. Thanks!Hexley21
I tested my app now,
dropLast(1) doesn't works, it deletes last character when dropLast(2), don't you know the reason?Tenfour04
test.isNotEmpty() && test.last() can be replaced with test.lastOrNull(). |
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
}
X,Y,ZYou want to replace this last character toA. Otherwise, You don't want to do anything?