Algorithm to detect how many words typed, also multi sentence support (Java)

Posted by Alex Cheng on Stack Overflow See other posts from Stack Overflow or by Alex Cheng
Published on 2010-04-30T13:22:03Z Indexed on 2010/04/30 13:27 UTC
Read the original article Hit count: 332

Filed under:
|

Hello all.

Problem:

I have to design an algorithm, which does the following for me:

Say that I have a line (e.g.)

alert tcp 192.168.1.1 (caret is currently here)

The algorithm should process this line, and return a value of 4.

I coded something for it, I know it's sloppy, but it works, partly.

private int counter = 0;
    public void determineRuleActionRegion(String str, int index) {
        if (str.length() == 0 || str.indexOf(" ") == -1) {
            triggerSuggestionList(1);
            return;
        }

        //remove duplicate space, spaces in front and back before searching
        int num = str.trim().replaceAll(" +", " ").indexOf(" ", index);
        //Check for occurances of spaces, recursively
        if (num == -1) { //if there is no space
            //no need to check if it's 0 times it will assign to 1
            triggerSuggestionList(counter + 1);
            counter = 0;
            return; //set to rule action
        } else { //there is a space
            counter++;
            determineRuleActionRegion(str, num + 1);
        }

    } //end of determineactionRegion()

So basically I find for the space and determine the region (number of words typed). However, I want it to change upon the user pressing space bar <space character>.

How may I go around with the current code?

Or better yet, how would one suggest me to do it the correct way? I'm figuring out on BreakIterator for this case...

To add to that, I believe my algorithm won't work for multi sentences. How should I address this problem as well.

--

The source of String str is acquired from textPane.getText(0, pos + 1);, the JTextPane.

Thanks in advance. Do let me know if my question is still not specific enough.

© Stack Overflow or respective owner

Related posts about java

Related posts about algorithm