Scala Iterate Over String

1. Introduction

Strings in Scala, as in many programming languages, can be iterated over as a sequence of characters. Scala provides various ways to iterate over a string, each method having its own use cases and advantages. This post will demonstrate different methods to iterate over a string in Scala.

2. Program Steps

1. Define a string to iterate over.

2. Use various methods such as foreach, for comprehension, map, and more to iterate over the string.

3. Print results to demonstrate how each method works.

4. Execute the program to showcase different ways of string iteration.

3. Code Program

object StringIterationDemo extends App {
  val myString: String = "Hello Scala"

  // Using foreach
  println("Using foreach:")
  myString.foreach(println)

  // Using for comprehension
  println("\nUsing for comprehension:")
  for (char <- myString) {
    println(char)
  }

  // Using map
  println("\nUsing map to transform each character:")
  val asciiValues = myString.map(_.toInt)
  asciiValues.foreach(println)

  // Using iterator
  println("\nUsing iterator:")
  val iterator = myString.iterator
  while (iterator.hasNext) {
    println(iterator.next())
  }

  // Using zipWithIndex
  println("\nUsing zipWithIndex:")
  myString.zipWithIndex.foreach { case (char, index) =>
    println(s"Character at index $index is $char")
  }
}

Output:

Using foreach:
H
e
l
l
o
S
c
a
l
a
Using for comprehension:
H
e
l
l
o
S
c
a
l
a
Using map to transform each character:
72
101
108
108
111
32
83
99
97
108
97
Using iterator:
H
e
l
l
o
S
c
a
l
a
Using zipWithIndex:
Character at index 0 is H
Character at index 1 is e
Character at index 2 is l
Character at index 3 is l
Character at index 4 is o
Character at index 5 is
Character at index 6 is S
Character at index 7 is c
Character at index 8 is a
Character at index 9 is l
Character at index 10 is a

Explanation:

1. foreach iterates over each character of myString, printing them.

2. For comprehension provides a more readable way to iterate over characters in the string.

3. map is used to transform each character to its ASCII value.

4. Using an iterator gives us manual control over the iteration, allowing us to traverse the string character by character.

5. zipWithIndex combines each character with its index, allowing us to print the position of each character in the string.


Comments