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-21 9:53

Why don't you just strip all punctuation from the string with replaceAll and then split it around blank character groups (using the regex \\s+).  Making it all one case will probably help too.

String str = "This test string is a test.";
str = str.toLowerCase();
str = str.replaceAll(".", " "); // simple example; the first parameter uses regex/real expression codes
String[] ary = str.split("\\s+");


Array ary should have the contents: [this][test][string][is][a][test]

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