Scala: Extracting Substrings From Strings

Many times you will be required to extract a substring out of a string. Since Scala is interoperable with Java, you can use Java's powerful String methods to extract substrings. I will update this page later with extracting strings using regular expressions. C++ Codes Beginners

I assume that you know how to read the API documentation. So I will be skipping some details.

Scala uses Java's String class for its own Strings. So any method that is defined in the Java documentation for the String will be available for use in Scala. You can read the Java documentation for String at http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html

I will be using the #substring method of the String class to extract substrings from Strings. The substring method comes in two variants. The first variant is the substring(start index,end index) and the next variant is the substring(start index). The first method variant will start extracting the string from the start index up to the end index but not including the end index. The second variant will start extracting the string the start index up to the end of the string.

Let us say that you have string A = "hello" and you want to extract the first three letters from it. You can call

A.substring(0,3) to achieve that.



However, using #substring can result in an IndexOutOfBoundsException if a) the start index is negative or larger than the string itself or b) the length is greater than the length of the string plus start index.

A more secure method of extracting substrings from a string is using the drop and take methods that are available on Strings in Scala.

"Exhaust".drop(2).take(5) will produce the string haust, so will "Exhaust".drop(2).take(15), with no exception being thrown.

If in doubt, you should probably use drop/take.