Hello, I want to know how many letters a word has (including spaces) through a for loop in Kotlin, this is the code that sends me an error
var palabra ="hola"
for(x :Int in palabra.length ){
println(x)
}
it should be noted that I am just starting to use the for loop thanks for your help again
The for loop is a utility to traverse member by member of an element made up of more elements or a defined range of values. The problem you have there is that you are trying to access every member of a number and Kotlin has no members in a number so the operation is invalid.
First, the query that occurs when writing
palabra.length
makes it return a number containing the number of letters in your word variable, since this is not a range, then it does not work for you. If you only want to see the length of a specific word you can write:If you want to go through each of the members of the variable
palabra
and do operations with each of its members (each letter) you have several options:A for loop that loops through each member and prints each member (letter)
A for loop that iterates through the range from 0 to word.length and stores a value in the variable i, then iterates through the i element of the word and prints it