Scala 子字符串函数

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

Scala subString function

scalafunctional-programming

提问by John

Hi I am looking for a solution it will return a substring from string for the given indexes.For avoiding index bound exception currently using if and else check.Is there a better approach(functional).

嗨,我正在寻找一种解决方案,它将为给定的索引从字符串返回一个子字符串。为了避免当前使用 if 和 else 检查的索引绑定异常。是否有更好的方法(功能)。

def subStringEn(input:String,start:Int,end:Int)={
  // multiple if check for avoiding index out of bound exception
    input.substring(start,end)
}

回答by Tzach Zohar

Not sure what you want the function to do in case of index out of bound, but slicemight fit your needs:

不确定在索引超出范围的情况下您希望该函数做什么,但slice可能符合您的需求:

input.slice(start, end)

Some examples:

一些例子:

scala> "hello".slice(1, 2)
res6: String = e

scala> "hello".slice(1, 30)
res7: String = ello

scala> "hello".slice(7, 8)
res8: String = ""

scala> "hello".slice(0, 5)
res9: String = hello

回答by prayagupd

Tryis one way of doing it. The other way is applying substring only if length is greater than end using Option[String].

Try是一种方法。另一种方法是仅当长度大于 end using 时才应用子字符串Option[String]

invalid end index

无效的结束索引

scala> val start = 1
start: Int = 1

scala> val end = 1000
end: Int = 1000

scala> Option("urayagppd").filter(_.length > end).map(_.substring(start, end))
res9: Option[String] = None

valid end index

有效的结束索引

scala> val end = 6
end: Int = 6

scala> Option("urayagppd").filter(_.length > end).map(_.substring(start, end))
res10: Option[String] = Some(rayag)

Also, you can combine filterand mapto .collectas below,

此外,您还可以结合filtermap.collect如下,

scala> Option("urayagppd").collect { case x if x.length > end => x.substring(start, end) }
res14: Option[String] = Some(rayag)

scala> val end = 1000
end: Int = 1000

scala> Option("urayagppd").collect { case x if x.length > end => x.substring(start, end) }
res15: Option[String] = None