Home > Software engineering >  I want to make method to replace all occurrences in string with a new variable using recursion
I want to make method to replace all occurrences in string with a new variable using recursion

Time:05-26

I implemented this method which just replaces all the occurrences of a string (oldVar) with the new string (newVar) in the original String f:

def replace(oldvar: Var, newvar: Var): String = 
  f.toString.replace(oldvar.toString, newvar.toString)

Works fine, but I'm looking for a recursive approach.

CodePudding user response:

This is a version that works on strings. You should create a custom one that works on Var by delegating to my version after casting Vars to string:

def replace(old: String, neo: String)(f: String): String = 
    if f.isEmpty then
        f
    else if f.startsWith(old) then 
        neo   replace(old, neo)(f.substring(old.length))
    else
        f.charAt(0).toString   replace(old, neo)(f.substring(1)) 

Also edge cases such as empty values for old, neo and f should be properly handled by you to avoid "index out of bounds" or infinite recrsion errors.

CodePudding user response:

This is cheating a little, but if you just want recursion ... (not really a fan of solving a straightforward problem in a runaround way "just because").

def replace(s: String, old: String, new_: String): String = s.indexOf(old) match {
  case -1 => s
  case x => s.substring(0, x)   new_   replace(s.substring(x   old.length), old, new_)
}

Caveat emptor! This is not a good solution, just the easiest one that satisfies your (quite unreasonable) requirement.

A good one, would at a minimum be (1) tail-recursive and (2) not glue strings together like this (which is rather inefficient). But then, again, we already know that the best solution is to just call .replace, so ... why bother?

  • Related