string 从字符串 Scala 的末尾删除字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1822481/
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 00:35:02  来源:igfitidea点击:

Remove Characters from the end of a String Scala

stringscala

提问by BefittingTheorem

What is the simplest method to remove the last character from the end of a String in Scala?

在 Scala 中从字符串末尾删除最后一个字符的最简单方法是什么?

I find Rubys String class has some very useful methods like chop. I would have used "oddoneoutz".headOption in Scala, but it is depreciated. I don't want to get into the overly complex:

我发现 Rubys String 类有一些非常有用的方法,比如chop。我会在 Scala 中使用 "oddoneoutz".headOption,但它已贬值。我不想陷入过于复杂的:

string.slice(0, string.length - 1)

Please someone tell me there is a nice simple method like chop for something this common.

请有人告诉我,对于这种常见的东西,有一个很好的简单方法,比如剁碎。

回答by Don Mackenzie

How about using dropRight, which works in 2.8:-

使用在 2.8 中有效的 dropRight 怎么样:-

"abc!".dropRight(1)

Which produces "abc"

产生“abc”

回答by Walter Chang

string.init // padding for the minimum 15 characters

回答by David Winslow

val str = "Hello world!"
str take (str.length - 1) mkString

回答by Stefan Kendall

string.reverse.substring(1).reverse

That's basically chop, right? If you're longing for a chop method, why not write your own StringUtilslibrary and include it in your projects until you find a suitable, more generic replacement?

这基本上是砍,对吧?如果您渴望使用chop 方法,为什么不编写自己的StringUtils库并将其包含在您的项目中,直到找到合适的、更通用的替代方法?

Hey, look, it's in commons.

嘿,看,它是公共的。

Apache Commons StringUtils.

阿帕奇公地StringUtils

回答by Andriy Plokhotnyuk

If you want the most efficient solution than just use:

如果您想要最有效的解决方案,而不仅仅是使用:

str.substring(0, str.length - 1)