string 在 Scala 中修剪字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17995260/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 02:02:28  来源:igfitidea点击:

Trimming strings in Scala

stringscala

提问by yAsH

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

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

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

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

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

在 Scala 中是否有任何内置方法可以做到这一点?

回答by Dirk

Try

尝试

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)

which would also take care of strings like ",,, ,,hello"

它还可以处理像这样的字符串 ",,, ,,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)
}

Use like

使用喜欢

stripAll(stringToCleanUp, charactersToRemove)

e.g.,

例如,

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

回答by lreeder

To trim the start and ending character in a string, use a mix of drop and dropRight:

要修剪字符串中的开始和结束字符,请混合使用 drop 和 dropRight:

scala> " hello,".drop(1).dropRight(1)

res4: String = hello

Scala>“你好,”.drop(1).dropRight(1)

res4:字符串=你好

The drop call removes the first character, dropRight removes the last. Note that this isn't "smart" like trim is. If you don't have any extra character at the start of "hello,", you will trim it to "ello". If you need something more complicated, regex replacement is probably the answer.

drop 调用删除第一个字符,dropRight 删除最后一个字符。请注意,这不像修剪那样“智能”。如果在“hello,”的开头没有任何多余的字符,则将其修剪为“ello”。如果您需要更复杂的东西,正则表达式替换可能是答案。

回答by Jean-Philippe Pellet

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 reversehere is because there is no dropRightWhile.

使用reverse这里是因为没有dropRightWhile.

If you're looking at a single possible comma, stripPrefixand stripSuffixare the way to go, as indicated by Dirk.

如果您正在查看单个可能的逗号,stripPrefix并且stripSuffix是要走的路,正如 Dirk 所指出的那样。

回答by chaotic3quilibrium

Given you only want to trim off invalid characters from the prefixand the suffixof a given string (not scan through the entire string), here's a tiny trimPrefixSuffixCharsfunction to quickly perform the desired effect:

鉴于您只想从给定字符串的前缀后缀中删除无效字符(而不是扫描整个字符串),这里有一个小trimPrefixSuffixChars函数可以快速执行所需的效果:

def trimPrefixSuffixChars(
    string: String
  , invalidCharsFunction: (Char) => Boolean = (c) => c == ' '
): String =
  if (string.nonEmpty)
    string
      .dropWhile(char => invalidCharsFunction(char))  //trim prefix
      .reverse
      .dropWhile(char => invalidCharsFunction(char)) //trim suffix
      .reverse
  else
    string

This function provides a default for the invalidCharsFunctiondefining only the space (" ") character as invalid. Here's what the conversion would look like for the following input strings:

此函数为invalidCharsFunction仅将空格 (" ") 字符定义为无效提供了默认值。以下是以下输入字符串的转换情况:

trimPrefixSuffixChars(" Tx  ")     //returns "Tx"
trimPrefixSuffixChars(" . Tx . ")  //returns ". Tx ."
trimPrefixSuffixChars(" T x  ")    //returns "T x"
trimPrefixSuffixChars(" . T x . ") //returns ". T x ."

If you have you would prefer to specify your own invalidCharsFunctionfunction, then pass it in the call like so:

如果您希望指定自己的invalidCharsFunction函数,请在调用中传递它,如下所示:

trimPrefixSuffixChars(",Tx. ", (c) => !c.isLetterOrDigit)     //returns "Tx"
trimPrefixSuffixChars(" ! Tx # ", (c) => !c.isLetterOrDigit)  //returns "Tx"
trimPrefixSuffixChars(",T x. ", (c) => !c.isLetterOrDigit)    //returns "T x"
trimPrefixSuffixChars(" ! T x # ", (c) => !c.isLetterOrDigit) //returns "T x"

This attempts to simplify a number of the example solutions provided in other answers.

这试图简化其他答案中提供的许多示例解决方案。

回答by Pianosaurus

Someone requested a regex-version, which would be something like this:

有人要求一个正则表达式版本,它会是这样的:

val result = " , ,, hello, ,,".replaceAll("""[,\s]+(|.*[^,\s])[,\s]+""", "''")

Result is: result: String = hello

结果是: result: String = hello

The drawback with regexes (not just in this case, but always), is that it is quite hard to read for someone who is not already intimately familiar with the syntax. The code is nice and concise, though.

正则表达式的缺点(不仅在这种情况下,而且总是如此),对于尚未非常熟悉语法的人来说,它很难阅读。不过,代码很好而且简洁。