【问题标题】:Scala subString function斯卡拉子字符串函数
【发布时间】:2017-06-09 02:52:34
【问题描述】:
您好,我正在寻找一种解决方案,它将为给定的索引从字符串中返回一个子字符串。为了避免当前使用 if 和 else 检查的索引绑定异常。是否有更好的方法(功能性)。
def subStringEn(input:String,start:Int,end:Int)={
// multiple if check for avoiding index out of bound exception
input.substring(start,end)
}
【问题讨论】:
标签:
scala
functional-programming
【解决方案1】:
不确定在索引超出范围时您希望函数做什么,但slice 可能满足您的需求:
input.slice(start, end)
一些例子:
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
【解决方案2】:
Try 是一种方法。另一种方法是仅当长度大于使用Option[String] 的结尾时才应用子字符串。
结束索引无效
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
有效结束索引
scala> val end = 6
end: Int = 6
scala> Option("urayagppd").filter(_.length > end).map(_.substring(start, end))
res10: Option[String] = Some(rayag)
另外,您可以将filter 和map 组合成.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