GameOfThrows
GameOfThrows

Reputation: 4510

scala replace string with underscore joined

I have a general question about how to replacing string parts.

Say I have 2 Strings:

a = "i am going to watch game of throne tonight on my throne"
b = "game_of_throne"

What is the most efficient way to replace game of throne with game_of_throne (i.e adding the under score to treat it as one string subject). If I do something like regex:

val c = """_""".r.replaceAllIn(b," ").r
val c.replaceAllIn(a, c) How do I actually ask it to draw the underscore?

I am trying to avoid splitting the String since it often increases computation time by quite a lot.

EDIT: I have a million pair of these, so I need to be able to use map and variable a and b.

Upvotes: 0

Views: 222

Answers (2)

Puneeth Reddy V
Puneeth Reddy V

Reputation: 1578

Hope this can help you.

object TestRegular extends App{
        val  a = "i am going to watch game of throne tonight on my throne"
        val c = """game of throne""".r.replaceAllIn(a,"game_of_throne")
        println(c)
}

Upvotes: 0

nattyddubbs
nattyddubbs

Reputation: 2095

a.replaceAll(b.replaceAll("_", " "), b)

Not sure if there is a more pure Scala way to do this but this should do.

Upvotes: 1

Related Questions