简体   繁体   中英

A way to remove specific characters from a string? (kotlin)

So I have a textField where you should enter your "coded" text and get it translated back to non-coded language by using .replace to remove certain characters. But I can't get it to work.

There is a kids "code-language" where you take a word, like cat and for every consonant you add an "o" and the consonant again. So a "b" would be "bob". With vowels they just stay as they are. Cat would be cocatot.

fun translateBack(view : View) {
     val konsonanter = "bcdfghjklmnpqrstvwxzBCDFGHJKLMNPQRSTVWXZ"
     var input = editText.text.toString()
     var emptyString = ""

     for(i in konsonanter) {
        val find_text = i + "o" + i

        var conso = i.toString()

        textView.text = input.replace(find_text, conso, false)
     }
 }

Would like for it to remove the two following letters for every consonant (if possible). So if i enter "cocowow" I should get out "cow". Right now I just get back what I enter in the textField...

Use a forEach loop through the chars of input and replace:

konsonanter.forEach { input = input.replace("${it}o${it}", "${it}", false) }
textView.text = input

The issue is that you're setting the text in textView in every loop, and never updating input . So you're essentially only seeing the result of the replace call that happens with the "ZoZ" and "Z" parameters at the end of the loop, with input still being the original string.

Instead, you can keep updating input and then set the text when you're done:

val konsonanter = "bcdfghjklmnpqrstvwxzBCDFGHJKLMNPQRSTVWXZ"
var input = editText.text.toString()
var emptyString = ""

for (i in konsonanter) {
    val find_text = i + "o" + i

    val conso = i.toString()

    input = input.replace(find_text, conso, false)
}

textView.text = input

If you use the replace function with a Regex and a transform function as parameters you can create a really concise completely self-containing extension function:

fun String.translateBack() = with(Regex("([bcdfghjklmnpqrstvwxz])o\\1", RegexOption.IGNORE_CASE)) {
    replace(this) { "${it.value.first()}" }
}

Explanation:

The Regex will match all same consonants (no matter the case) around an "o". To ensure that the consonant before and after the "o" are the same a backreference to the first group was used.

So, this will also work for cases like "coCatot".

Usage:

println("bob".translateBack()) // b
println("cocatot".translateBack()) // cat
println("coCatot".translateBack()) // cat

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM