8

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.

2
  • To be sure. If the String ends with X, Y, Z You want to replace this last character to A. Otherwise, You don't want to do anything? Commented Aug 31, 2020 at 11:00
  • Absolutely right Commented Aug 31, 2020 at 11:01

3 Answers 3

5

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"
Sign up to request clarification or add additional context in comments.

9 Comments

instead of substring(0, test.length - 1) you can use dropLast(1)
first one is better. Thank you!
@Stachu It looks better with dropLast(1), I edited my answer. Thanks!
I tested my app now, dropLast(1) doesn't works, it deletes last character when dropLast(2), don't you know the reason?
test.isNotEmpty() && test.last() can be replaced with test.lastOrNull().
|
4

Simply use this regexp:

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

$ in regex means last character of a string

Comments

3

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.