Trimming strings in Scala

前端 未结 5 1959
无人共我
无人共我 2020-12-25 10:19

How do I trim the starting and ending character of a string in Scala

For inputs such as \",hello\" or \"hello,\", I need the output as

5条回答
  •  南笙
    南笙 (楼主)
    2020-12-25 11:22

    If you want to trim only commas and might have more than one on either end, you could do this:

    str.dropWhile(_ == ',').reverse.dropWhile(_ == ',').reverse
    

    The use of reverse here is because there is no dropRightWhile.

    If you're looking at a single possible comma, stripPrefix and stripSuffix are the way to go, as indicated by Dirk.

提交回复
热议问题