Home > Mobile >  Kotlin query: Replace all the words in the string starting and ending with $ e.g. $lorem$ to <i&g
Kotlin query: Replace all the words in the string starting and ending with $ e.g. $lorem$ to <i&g

Time:12-10

I am stuck on the following code challenge in Kotlin:

Replace all the words in the string starting and ending with $ e.g. $lorem$ to <i>lorem</i>

var incomingString = "abc 123 $Lorem$,  $ipsum$, $xyz$ 547"

// My non working code:

fun main(args: Array<String>) {

    val incomingString = "abc 123 \$Lorem$,  \$ipsum$, \$xyz$ 547";
    var finalString = "";


    println(filteredValue)
    if (incomingString.contains("$")){
        val intermediateString = incomingString.replace("\$", "<i>")
        finalString = "$intermediateString</i>"
    }

   println(finalString)
}

Output is:

abc 123 <i>Lorem<i>,  <i>ipsum<i>, <i>xyz<i> 547</i>

Desired output:

abc 123 <i>Lorem</i>,  <i>ipsum</i>, <i>xyz</i> 547</i>

CodePudding user response:

I am not going to do your home work for you, but the reason why you have a challenge including $ is that symbol has two special purposes

  1. Read up about String Interpolation in Kotlin: https://kotlinlang.org/docs/idioms.html#string-interpolation ... you will need to take care to prevent the $ being used for interpolation ... and seems you already got that part
  2. $ is also a special character in Regular Expressions. Regular Expressions are an esoteric area of programming - meaning very complicated to get your head around, but very very powerful. Worth the effort. Using Regular Expression (Regex) approach for this program is what will get you lots of marks if you can also be sure to escape the $. Here is the Kotlin Regex replace function docs: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/-regex/replace.html

CodePudding user response:

Every time you come across a $ in your input string, you need to alternate between replacing it with <i> and replacing it with </i>. Therefore, you need to have a variable that tells you what state you're in, and every time you make a replacement, you flip that variable. You may find Kotlin's String.replaceFirst method useful.

  • Related