CMPE
CMPE

Reputation: 1963

Scala: Remove the last occurrence of a character

I am trying to remove the last occurrence of a character in a string. I can get its index:

str.lastIndexOf(',')

I have already tried to use split and the replace function on the string.

Upvotes: 5

Views: 11819

Answers (4)

Techmag
Techmag

Reputation: 1391

Curious why Scala doesn't have a .replaceLast but there must be a reason...

Reverse the String and use str.replaceFirst then reverse again

I doubt this is terrible efficient but it is effective :)

scala> "abc.xyz.abc.xyz".reverse.replaceFirst("zyx.", "").reverse
res5: String = abc.xyz.abc

As a def it would look like this:

def replaceLast(input: String, matchOn: String, replaceWith: String) = {
  input.reverse.replaceFirst(matchOn.reverse, replaceWith.reverse).reverse
}

Upvotes: 1

Paweł Jurczenko
Paweł Jurczenko

Reputation: 4471

You could try the following:

val input = "The quick brown fox jumps over the lazy dog"
val lastIndexOfU = input.lastIndexOf("u")
val splits = input.splitAt(lastIndexOfU)
val inputWithoutLastU = splits._1 + splits._2.drop(1) // "The quick brown fox jmps over the lazy dog"

Upvotes: 0

Kevin Meredith
Kevin Meredith

Reputation: 41909

scala> def removeLast(x: Char, xs: String): String = {
     |   
     |   val accumulator: (Option[Char], String) = (None, "")
     |   
     |   val (_, applied) =  xs.foldRight(accumulator){(e: Char, acc: (Option[Char], String)) =>
     |       val (alreadyReplaced, runningAcc) = acc
     |       alreadyReplaced match {
     |            case some @ Some(_) => (some, e + runningAcc)
     |            case None           => if (e == x) (Some(e), runningAcc) else (None, e + runningAcc)
     |         }
     |   }
     | 
     |   applied
     | }
removeLast: (x: Char, xs: String)String

scala> removeLast('f', "foobarf")
res7: String = foobar

scala> removeLast('f', "foobarfff")
res8: String = foobarff

Upvotes: 0

jwvh
jwvh

Reputation: 51271

You could use patch.

scala> val s = "s;dfkj;w;erw"
s: String = s;dfkj;w;erw

scala> s.patch(s.lastIndexOf(';'), "", 1)
res6: String = s;dfkj;werw

Upvotes: 18

Related Questions