在 Scala 中修剪字符串 [英] Trimming strings in Scala

查看:35
本文介绍了在 Scala 中修剪字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Scala 中修剪字符串的开始和结束字符

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

对于诸如 ",hello""hello," 之类的输入,我需要输出为 "hello".

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

Scala 中是否有任何内置方法可以执行此操作?

Is there is any built-in method to do this in Scala?

推荐答案

尝试

val str = "  foo  "
str.trim

并查看文档.如果您也需要去掉 , 字符,您可以尝试以下操作:

and have a look at the documentation. If you need to get rid of the , character, too, you could try something like:

str.stripPrefix(",").stripSuffix(",").trim

另一种清理字符串前端的方法是

Another way to clean up the front-end of the string would be

val ignoreable = ", \t\r\n"
str.dropWhile(c => ignorable.indexOf(c) >= 0)

它也会处理像 ",,,,,,hello" 之类的字符串

为了更好的衡量,这里有一个小函数,它在字符串中从左到右一次扫描:

And for good measure, here's a tiny function, which does it all in one sweep from left to right through the string:

def stripAll(s: String, bad: String): String = {

    @scala.annotation.tailrec def start(n: Int): String = 
        if (n == s.length) ""
        else if (bad.indexOf(s.charAt(n)) < 0) end(n, s.length)
        else start(1 + n)

    @scala.annotation.tailrec def end(a: Int, n: Int): String =
        if (n <= a) s.substring(a, n)
        else if (bad.indexOf(s.charAt(n - 1)) < 0) s.substring(a, n)
        else end(a, n - 1)

   start(0)
}

使用喜欢

stripAll(stringToCleanUp, charactersToRemove)

例如

stripAll("  , , , hello , ,,,, ", " ,") => "hello"

这篇关于在 Scala 中修剪字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆