9

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)
}

2 Answers 2

18

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
Sign up to request clarification or add additional context in comments.

Comments

5

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.