Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace last character in String when it is in an Array

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.

like image 879
Hexley21 Avatar asked Aug 31 '20 10:08

Hexley21


People also ask

How do you replace the last occurrence of a character in a string?

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.

How do you remove the last character of an array?

use a . map() to get a new array and for each item do a . slice(0,-1) to remove the last char.

How do you replace last character in string Java?

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.

How do I remove characters from the end of a string?

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.


Video Answer


3 Answers

Simply use this regexp:

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

$ in regex means last character of a string

like image 154
Misha Akopov Avatar answered Nov 14 '22 23:11

Misha Akopov


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"
like image 27
iknow Avatar answered Nov 14 '22 23:11

iknow


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
}
like image 26
Nicola Gallazzi Avatar answered Nov 15 '22 01:11

Nicola Gallazzi