Word Counter - need help

Hi, guys,

I am creating a little application for medical students to practice writing patients notes. I need to introduce a word counter so that the length of the text in a given Text Area does not exceed a given number of words.

I found the following thread on this forum

https://forum.xojo.com/3440-the-wordcounter-example/0#p23223

This is the code that I am referring to


#pragma BackgroundTasks False
    #pragma BoundsChecking False
    #pragma NilObjectChecking False
    #pragma StackOverflowChecking False
    
    // new optimized method
    Dim count As Integer
    Dim wordLength As Integer
    
    dim mMB as MemoryBlock = mText
    Dim char As integer
    dim p as ptr = mMB
    Dim textLen As Integer = mMB.Size-1
    For i As Integer = 0 To textLen
      char = p.Byte(i)
      ' see if character is in ASCII A..Z or a..z range
      if (char >= 65 and char <= 90) or (char >= 97 and char <= 122) then
        wordLength = wordLength + 1
      else
        if wordLength >=1 then 
          count = count +1
          wordLength = 0 // reset word length to zero
        end if
      end if
    Next
    
    Return count

I am going to set a variable Textarea1_WordCount as integer.

Then I will set a Timer to perform word counting every 10 seconds (I do not want the Timer to interfere with the student’s typing).

How should I modify the code above so that it counts words in the given Text Area and passes the result the TextArea1_WordCount variable?

Thank you in advance,

Val

From Paul’s response on the referenced thread…

For your purposes:

dim totWords() As string = split(TextArea1.text, chr(32)) wordsInFld = ubound(totWords) + 1

[quote=414024:@Roger Clary]From Paul’s response on the referenced thread…

For your purposes:

dim totWords() As string = split(TextArea1.text, chr(32)) wordsInFld = ubound(totWords) + 1[/quote]
but that would mis-count

[quote]abc , def , xyz[/quote] would be 5 “words”

[quote]abc,def,xyz[/quote] would only be 1
“context” would matter

I’d using a regular expression for this. In the Timer’s Action (which can run every 750 ms, really), try something like this:

dim count as integer
dim rx as new RegEx
rx.SearchPattern = "\\b\\w+\\b"

dim match as RegExMatch = rx.Search( TextArea1.Text )
while match isa object
  count = count + 1
  match = rx.Search
wend

TextArea1_WordCount = count

Unless you expect the text to get really long, I wouldn’t expect the user to notice this code.