Scala subString function
21,556
Solution 1
Not sure what you want the function to do in case of index out of bound, but slice
might fit your needs:
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
Solution 2
Try
is one way of doing it. The other way is applying substring only if length is greater than 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 filter
and map
to .collect
as below,
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
Author by
John
Updated on June 09, 2020Comments
-
John almost 4 years
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).
def subStringEn(input:String,start:Int,end:Int)={ // multiple if check for avoiding index out of bound exception input.substring(start,end) }