Scala: Remove the last occurrence of a character

限于喜欢 提交于 2020-01-04 04:10:08

问题


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.


回答1:


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



回答2:


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



回答3:


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"


来源:https://stackoverflow.com/questions/37945653/scala-remove-the-last-occurrence-of-a-character

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!