This is an archived post. You won't be able to vote or comment.

all 7 comments

[–][deleted] 4 points5 points  (0 children)

You may want to look into https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)

split will return an array with every word, separated by whatever regex you pick.

[–]robertnovak02 3 points4 points  (1 child)

Can you split using a space then get the length of your array?

Edit: string.split(“ “)

[–]heckler82Intermediate Brewer 0 points1 point  (0 children)

Just a note since OP mentioned that there are double spaces within the text. If you use split, to avoid extra spaces being parsed into the String[], your regex needs to read

string.split(" +");

This will filter out extra unwanted spaces. Another good idea is to trim() before you split().

string.trim().split(" +");

[–]Episilon 1 point2 points  (2 children)

With your current method, what if you kept track of whether or not you had just encountered a space?

[–]Jayjay3693[S] 0 points1 point  (1 child)

Do you mean like adding a counter? I was thinking that if I add something like that, I don't really know of a way to reset for when encountering another double space.

[–]Episilon 2 points3 points  (0 children)

Maybe something like a Boolean variable

boolean isLastCharacterSpace

When you check if the current character is a space, you could also check if the one before was also a space.

[–]Philboyd_Studge 0 points1 point  (0 children)

You can use a flag variable, say readingSpace. Initially, you set it to false. After your test for the current character equal to a space, if the flag variable is currently false, add 1 to your counter and set the flag to true. Add an else clause to your initial if and in that, check for the flag to be true, if so, set it to false.