Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

String operations in Java

Name: Anonymous 2010-12-20 23:04

I'm learning about operations on strings, and I'm having trouble dealing with punctuation. Basically, I need to provide the count of each word in a given string. I have no problem with this, except that punctuation at the end of a word cannot be included.

For example, the string
"This test string is a test."
should yield to
this - 1
test - 2
string - 1
is - 1
a - 1

but instead I'm getting

test - 1
test. - 1

to further complicate matters, things like "..." is a word, and should be counted once. "derp.derp" is also a single word.

I have the logic, but I don't know how to execute it
if (word ends in punctuation and is preceded by non-punctuation)
   word = substring(0,word.length)

this gets pretty messy and I'm getting a lot of null pointers with spaces in between words for some reason.

I'll post some of my code after this.

Name: Anonymous 2010-12-20 23:06

//returns the whole thing with all words and their corresponding counts
private String allWordCounts(){
        initializeWords();
        String str = "";
        for(int x = 0; x < wordCount(); x++){
            if (!(words[x]).equals(""))
                str += words[x] + "\t\t" + countOf(words[x]) + "\n";
        }
        return str;
    }


//chops up the original string and puts individual words into an array. this is confirmed for working.
private void initializeWords(){
        int start = 0, end = trimmed.indexOf(' ',start), counter = 0;
        while(start < trimmed.length()){
            end = trimmed.indexOf(' ',start);
            if (end == -1)
                end = trimmed.length();
            words[counter] = trimmed.substring(start,end);
            counter++;
            start = end+1;
        }
    }

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List