Scala - String Functions with Examples

1. Introduction

Strings in Scala are sequences of characters. Scala offers a rich set of methods to work with strings, allowing developers to perform various operations easily and intuitively. This blog post will explain and demonstrate a list of common string functions provided by Scala.

List of Scala String Functions

Here's a brief overview of some common string functions in Scala:

length: Returns the number of characters in the string.

concat: Concatenates one string to the end of another.

indexOf: Returns the index within the string of the first occurrence of the specified character or substring.

substring: Returns a new string that is a substring of the given string.

startsWith: Tests if the string starts with the specified prefix.

endsWith: Tests if the string ends with the specified suffix.

toLowerCase: Converts all of the characters in the string to lower case.

toUpperCase: Converts all of the characters in the string to upper case.

replace: Returns a new string resulting from replacing all occurrences of oldChar in the string with newChar.

replaceAll: Replaces each substring that matches the given regular expression with the given replacement.

split: Splits the string around matches of the given regular expression.

trim: Returns a copy of the string, with leading and trailing whitespace omitted.

2. Program Steps

1. Define a string for demonstration.

2. Apply each string function to the string.

3. Print the result of each function.

4. Execute the program to verify the functionality.

3. Code Program

object StringFunctionsDemo extends App {
  val str: String = "Hello Scala!"

  // String length
  println(s"Length: ${str.length}")
  // Concatenate
  println(s"Concatenate: ${str.concat(" Let's learn together!")}")
  // Index of
  println(s"Index of 'Scala': ${str.indexOf("Scala")}")
  // Substring
  println(s"Substring (0,5): ${str.substring(0, 5)}")
  // StartsWith
  println(s"Starts with 'Hello': ${str.startsWith("Hello")}")
  // EndsWith
  println(s"Ends with '!': ${str.endsWith("!")}")
  // To lower case
  println(s"Lower case: ${str.toLowerCase}")
  // To upper case
  println(s"Upper case: ${str.toUpperCase}")
  // Replace
  println(s"Replace 'Scala' with 'World': ${str.replace("Scala", "World")}")
  // Replace all
  println(s"Replace all 'l' with 'L': ${str.replaceAll("l", "L")}")
  // Split
  val words: Array[String] = str.split(" ")
  println(s"Split by space: ${words.mkString(", ")}")
  // Trim
  println(s"Trim: ${"   Hello Scala!   ".trim}")
}

Output:

Length: 12
Concatenate: Hello Scala! Let's learn together!
Index of 'Scala': 6
Substring (0,5): Hello
Starts with 'Hello': true
Ends with '!': true
Lower case: hello scala!
Upper case: HELLO SCALA!
Replace 'Scala' with 'World': Hello World!
Replace all 'l' with 'L': HeLLo ScaLa!
Split by space: Hello, Scala!
Trim: Hello Scala!

Explanation:

1. We define a string str with the value "Hello Scala!".

2. The length function gives us the length of str, which is 12.

3. concat is used to append additional text to str, resulting in "Hello Scala! Let's learn together!".

4. indexOf searches for the position of the substring "Scala" within str, which is 6.

5. The substring function is used to get the first five characters of str, resulting in "Hello".

6. startsWith and endsWith check if str starts with "Hello" and ends with "!", respectively, both returning true.

7. toLowerCase and toUpperCase convert str to all lower case or upper case characters.

8. replace is used to replace "Scala" with "World" within str.

9. replaceAll changes all occurrences of "l" to "L".

10. split divides str into an array of words by spaces.

11. trim removes leading and trailing whitespace from a string, demonstrating with a modified version of str.


Comments