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.
To replace the last occurrence of a character in a string: Use the lastIndexOf() method to get the last index of the character. Call the substring() method twice, to get the parts of the string before and after the character to be replaced. Add the replacement character between the two calls to the substring method.
use a . map() to get a new array and for each item do a . slice(0,-1) to remove the last char.
Using Regular Expression We can also use the regular expression to remove or delete the last character from the string. The String class provides the replaceAll() method that parses two parameters regex and replacement of type String. The method replaces the string with the specified match.
Using String. The easiest way is to use the built-in substring() method of the String class. In order to remove the last character of a given String, we have to use two parameters: 0 as the starting index, and the index of the penultimate character.
Simply use this regexp:
val regEx = "[XYZ]$".toRegex()
val result = initialString.replace(regexp,"A")
$
in regex means last character of a string
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"
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With