string Scala - 从字符串中获取最后两个字符

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

Scala - Get last two characters from string

stringscala

提问by jhdevuk

How would I return the last two characters of a string?

我将如何返回字符串的最后两个字符?

回答by oxbow_lakes

Scala allows you to do this in a much cleaner way than the standard StringAPI by leveraging the collections API (for which there is an implicit conversion from a java.lang.Stringinto an IndexedSeq[Char]):

Scala 允许您String通过利用集合 API(其中存在从 ajava.lang.String到 an的隐式转换IndexedSeq[Char])以比标准API更简洁的方式执行此操作:

str takeRight 2

The fantastic thing about the API of course, is that it preserves the type representation of the original "collection" (i.e. Stringin this case)!

当然,API 的奇妙之处在于它保留了原始“集合”的类型表示(即String在这种情况下)!

回答by Govind Singh

you can use

您可以使用

.takeRight(2)


var keyword="helloStackoverFlow"

println(keyword.takeRight(2)) // ow

回答by Dinar Gataullin

You can take (string length -1) that reveal last index of your string, (string length -2) will be next character from end:

您可以使用 (string length -1) 显示字符串的最后一个索引,(string length -2) 将是从末尾开始的下一个字符:

str(str.length-1)+str(str.length-1)

str(str.length-1)+str(str.length-1)