2

I have a string with wrong directed paranthesis, I want to replace ( with ) and ) with ( at same time, can I do it with a single replace method or I should use a loop?

For example I have this string : You need extra time ) or money (

Which should be like this : You need extra time ( or money )

3
  • Please take a look at my update, it's very beautiful :D Commented Dec 21, 2017 at 7:19
  • great! I liked compressed expressions Commented Dec 21, 2017 at 7:47
  • 1
    This has little to do with concurrency, no? Commented Dec 21, 2017 at 8:04

1 Answer 1

2

Yes♂you♂can.

With the help of Regex, you can do a lot of things.

i.e. we have a "()":

"()".replace(Regex("[()]")) {
    when (it.value) {
        "(" -> ")"
        ")" -> "("
        else -> ""
    }
}

And the result is ")(" (I tested it under Kotlin 1.2.10).
This one is very readable.

A one-linear way, more tricky:

"()".replace(Regex("[()]")) { ")("["()".indexOf(it.value[0])].toString() }

This one is unreadable.

Sign up to request clarification or add additional context in comments.

2 Comments

"is unreadable, but looks better" - wut, this doesn't make sense! :)
I think a one-linear one is always better than a 7-line one... I'll edit it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.