Kotlin String - forEach() Function



The Kotlin string forEach() function is used to traverse or iterate through each character in the charSequence or string and uses a lambda expression to perform an action.

forEach is used for concise and readable character iteration and is more suitable for iterating over each element than a traditional for loop. It works seamlessly with strings because a string is a collection of characters.

Syntax

Following is the syntax of the Kotlin string forEach() function −

inline fun CharSequence.forEach(action: (Char) -> Unit)

Parameters

This function accepts a lambda function that takes a character as a parameter and performs an operation on it.

Return Value

This function does not return any value.

Example 1: Display Each Character

This is a basic example of forEach() function, here we display the each character of this string −

fun main() {
   val str = "Kotlin"
   str.forEach { char ->
      print(char+" ")
   }
}

Output

Following is the output −

K o t l i n 

Example 2: Perform an Action on Each Char

Following is the another example, performing an operation on each character using the forEach() function −

fun main() {
   val str = "TutorialS"
   str.forEach { char ->
      if (char.isUpperCase()) {
         println("$char is uppercase")
      } else {
         println("$char is lowercase")
     }
  }
}

Output

Following is the output −

T is uppercase
u is lowercase
t is lowercase
o is lowercase
r is lowercase
i is lowercase
a is lowercase
l is lowercase
S is uppercase

Example 3: Count Number of Char

The below example uses the forEach() function to count the number of characters in the string −

fun main() {
   val str = "tutorialspoint"
   var count = 0
   str.forEach { count++ }
   println("The string has $count characters.")
}

Output

Following is the output −

The string has 14 characters.
kotlin_strings.htm
Advertisements