Kotlin String Looping Example



This Kotlin example shows how te loop over a string using a for loop, forEach loop, and forEachIndexed loop.
A Kotlin string is a sequence of characters. We can loop this sequence.

Kotlin String Looping Example

The example loops over a string using a for loop, forEach loop, and forEachIndexed loop.
package net.javaguides.kotlin.examples

fun main(args: Array < String > ) {

    val phrase = "Source Code Examples"

    for (e in phrase) {

        print("$e ")
    }

    println()

    phrase.forEach {
        e - > print(String.format("%#x ", e.toByte()))
    }

    println()

    phrase.forEachIndexed {
        idx,
        e - > println("phrase[$idx]=$e ")
    }
}
Output:
S o u r c e   C o d e   E x a m p l e s 
0x53 0x6f 0x75 0x72 0x63 0x65 0x20 0x43 0x6f 0x64 0x65 0x20 0x45 0x78 0x61 0x6d 0x70 0x6c 0x65 0x73 
phrase[0]=S 
phrase[1]=o 
phrase[2]=u 
phrase[3]=r 
phrase[4]=c 
phrase[5]=e 
phrase[6]=  
phrase[7]=C 
phrase[8]=o 
phrase[9]=d 
phrase[10]=e 
phrase[11]=  
phrase[12]=E 
phrase[13]=x 
phrase[14]=a 
phrase[15]=m 
phrase[16]=p 
phrase[17]=l 
phrase[18]=e 
phrase[19]=s 
From the above program, we traverse the string with a for loop and print each of the characters:
for (e in phrase) {
    print("$e ")
}
We traverse over a loop with forEach and print a byte value of each of the characters:
phrase.forEach { e -> print(String.format("%#x ", e.toByte())) }
With forEachIndexed, we print the character with its index:
phrase.forEachIndexed { idx, e -> println("phrase[$idx]=$e ")  }

Comments