• 12
name

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 191

Backtrace:

File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 191
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

I have tried to read this thread: Android - java - count words

but it doesn't work for me.

so let say I have these words in the android multiline edit text:


I

am

very very

happy

right now


so I want to count the number of words and then get integer '7' from that multiline edit text. how to do that ?

I have tried this, but it doesn't work:

multilineEditText.addTextChangedListener(object: TextWatcher {

            override fun afterTextChanged(s: Editable?) {

            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

                val words = s.toString().trim()
                numberOfInputWords = words.split("\\s+").first().length
                wordsCounterTextView.text = "$numberOfInputWords"


            }

        })

but this code doesn't work for me, because it doesn't show the right number.

from the thread Android - java - count words

it is said that I can use someString.split("\\s+").length

but I can't access .length after using .split("\\s+"). like this

enter image description here

thats why I use first() in my code, even though it doesn't work either.

The only problem you have is you are using Kotlin's split method which returns a list of String whereas Java's split method returns an array of strings. You should be accessing size property since the return of split method here is List.

  val words = s.toString().trim()
  numberOfInputWords = words.split("\\s+".toRegex()).size
  wordsCounterTextView.text = "$numberOfInputWords"

Example for kotlin's split method

  • 1
Reply Report

So, you could count the words by the number of newlines and spaces between them. Of course consecutive newlines and consecutive spaces count as one.

There might be a space/newline at the beginning and end. You remove that with trim(). The last word won't have a space/newline now, so you need to add 1.

val string = "Hello\nWorld"
val count = Regex("""(\s+|(\r\n|\r|\n))""").findAll(string.trim()).count() + 1
println(count) // 2
  • 0
Reply Report