I'm trying to find out how many times one string appears in another. For my testing, I'm using "ea" for wordOne and "Ilikedthebestontheeastbeachleast" for wordTwo. My output is returning 0 for my "appearance" variable, which should store how many times "ea" appears in wordTwo.
Here's the relevant code section:
int wordTwoLength = wordTwo.length();
System.out.println(wordTwoLength);
while (wordTwoLength > 0)
{
positionCount = wordTwo.indexOf(wordOne, positionCount);
appearances = appearances++;
wordTwoLength = (wordTwoLength - positionCount);
}
System.out.println(appearances);
What do you mean by
appearances = appearances++;
This will make sure appearances is ZERO always.
Shouldn't it be just appearances++ ?
The problem is where you set the value of appearances. There's a difference between
appearances = appearances++;
and
appearances = ++appearances;
What you have will assign the value of appearances and then increment the 'old' appearances variable. You're going to want to increment it and then assign it.
Alternatively, you could just write
appearances++;
There are two bugs here.
One is that you've written appearances = appearances++; instead of just appearances++;. The effect of this is that appearances is incremented, and then reset to its previous value; in other words, there's no change.
The second bug is that you're beginning each search after the first, at the location where the match was found. So you're just finding the same match over and over. Your output will just therefore depend on how many times you can subtract positionCount before wordTwoLength becomes negative.
Here is how I would write this method, if I had to.
public int numberOfOccurrences(String toExamine, String toFind) {
int currentPosition = 0;
int occurrences = 0;
for(;;) {
int index = toExamine.indexOf(toFind, currentPosition);
if (index == -1) {
return occurrences;
}
currentPosition = index + toFind.length();
occurrences++;
}
}
I think this may be your problem. The line "appearances = appearances++;" will, in your case, set appearances to 0. This is because the ++ operator increments the variable but returns the original number. You just want to put "appearances++;".
I.e. it takes appearances (which is 0) adds 1 to it (making its value 1)and then returns 0. So basically the statement is equivalent to "appearances = 0;".
来源:https://stackoverflow.com/questions/19395153/while-loop-doesnt-run-a-indexof-search