-3
@SuppressLint("SetTextI18n")
private fun countName(x: String) {
    val textView: TextView = findViewById(R.id.result)
    for (i in 0 until x.length) {
        textView.text = i.toString()
    }
}

This is what I have so far. It works somewhat but for some reason it is lagging behind 1 number. For example, if I type James, the number it will output would be 4.

Ryan M
  • 18,333
  • 31
  • 67
  • 74
  • so then +1 to your result. your for starts at 0 – a_local_nobody Aug 25 '21 at 19:32
  • 1
    This logic doesn't really make sense, just setting `textView.text = x.length.toString()` would be identical, there's no need for a loop. – Henry Twist Aug 25 '21 at 19:33
  • 3
    Instead of you having to use a for loop, why don't you just use `textView.text = x.length.toString()`??? – Dương Minh Aug 25 '21 at 19:35
  • 2
    You don't need the loop, but the reason this isn't working is because ``x until y`` defines an range that **doesn't include** ``y`` - it's everything *up to* that value, which is why for "James" (length 5) the last loop you do is ``i == 4``. If you want an **inclusive** range (that includes the last value) you need to do ``x .. y`` – cactustictacs Aug 25 '21 at 21:19

2 Answers2

0

How to get the number of characters in a string (usually what you want):

str.length

How to get the number of Unicode code points in a string (because sometimes a code point is encoded as multiple characters):

str.codePointCount(0, str.length)

See this Java answer for more details on the difference between these two options.

Ryan M
  • 18,333
  • 31
  • 67
  • 74
  • (Also please let me know if this question is actually a duplicate of some Kotlin string length question. I couldn't find one when I looked.) – Ryan M Aug 26 '21 at 05:04
0

There are many simple ways to get the number of characters in a string. but if you want to know the mistake in your code you should have started to count from 1 instead of 0.

for (i in 1 until x.length) {
        textView.text = i.toString()
    }
vignesh
  • 492
  • 3
  • 9