Zahid Khan
Zahid Khan

Reputation: 5

What is the use of [i] in the below code?

fun main(args: Array<String>) {
var word= readLine()!!.toString()
var letter:Char='a'
println(CharCount(word,'a'))

}

fun CharCount(word:String, letter:Char):Int{
var a=0
var b=word
var length=b.length
for (i in 0 .. length-1){
    if (letter==b[i]) {
        a++
        }
    }
return a

}

Note: If someone please help to explain for loop part of this code like why we use [i] or what is it use? and a++ role

Upvotes: 0

Views: 38

Answers (1)

Andr&#225;s Hummer
Andr&#225;s Hummer

Reputation: 972

Strings are character arrays. Here the i goes from 0 to the length of the word (minus 1), practically iterating through the word's letters. Here the [i] as the current cell position within the array marks the (i+1)th letter of the word. This part of code counts the occurrence of the letter letter in the word word. The function compares each letter of the word with its second parameter. Every time there is a match a is incremented by 1. In the end a returns how many times said letter is present in the word.

Upvotes: 2

Related Questions