How to check the number of words in a String?

Asked

Viewed 178 times

-1

Well, I’m doing a job for college where I need to identify the number of words that a string has in Kotlin.

Type :

texto = "Ola Mundo"

The variable numeropalavras has to be equal to 2.

Is there a function that checks the number of words, without me having to cycle to check letter by letter to find the number of words?

1 answer

1

You can separate the string by the spaces between the words using the function split() and see the size (length) of the array.

val string = "Uma string de exemplo"
val numeropalavras = string.split(" ").length

Browser other questions tagged

You are not signed in. Login or sign up in order to post.