Tuesday 24 May 2016

Scala for Beginners (Part-2): slice function in String

Introduction

I have already discussed about slice function usage in Collection API and Arrays in my previous post. You can access that tutorial here:   "Slice in Collection API and Array"


In this post, we are going to discuss the following two things

  • How slice function works of String class
  • Difference between slice and substring functions of String class
  • Any Difference between slice and substring functions of String class

The 'slice' function usage:

In Scala API, 'slice' function is used to select an interval of elements. It takes two parameters of Int type as shown below:

slice function syntax:



    def slice(from-index: Int, until-index: Int): Seq[A] 



Parameter Usage
Frist Starting index (Inclusive). It should be zero or any any positive integer less than the length of the Collection or String or Array.
Second Ending index (Exclusive).

String slice function Examples:

scala> val str = "Hello I'm doing good. How are you?"

str: String = Hello I'm doing good. How are you?

scala> str.slice(6,9)


res8: String = I'm

As we know, String index starts with zero.
Here from-index = 6 means 
until-index = 9 (It's exclusive so we need to consider till index = 8 only)

String's substring function works same as it's slice function as shown below:

scala> str.substring(6,9)
res12: String = I'm

Here both str.slice(6,9) and str.substring(6,9) are returning same value. 

Difference between slice and substring functions of String class

  • Functionality wise and syntax wise there is no difference
  • Performance is almost similar and ignorable.

NOTE:- In Scala, We can access String characters just like an Array elements as shown below:

scala> str(0)
res0: Char = H

Here it returns a Char, but not a String

scala> str(-1)
java.lang.StringIndexOutOfBoundsException: String index out of range: -1
  at java.lang.String.charAt(String.java:658)
  at scala.collection.immutable.StringOps$.apply$extension(StringOps.scala:38)
  ... 33 elided

scala> str.length
res2: Int = 34

scala> str(34)
java.lang.StringIndexOutOfBoundsException: String index out of range: 34
  at java.lang.String.charAt(String.java:658)
  at scala.collection.immutable.StringOps$.apply$extension(StringOps.scala:38)

  ... 33 elided


NOTE:- If we try to access String characters in out of range, we get StringIndexOutOfBoundsException as shown above.


String's character access returns Char where as substring & slice functions returns String as shown below.

scala> str(0)
res4: Char = H

scala> str.substring(0,1)
res5: String = H

scala> str.slice(0,1)
res6: String = H


That's it about slice function in Scala.

Thank you for reading my posts.
Please drop me a comment if you like my posts or have any suggestions or questions.

No comments:

Post a Comment