简体   繁体   中英

How to count number of string occurrences within string (with overlap)

This is what I have written so far. Unfortunately, my code is only counting string occurrences without overlap. If anyone could point me in the right direction that would be great!

Here are some examples:

howManyWithOverlap("asdfgasjkasiuas", "as") returns 4

howManyWithOverlap("baaaaaac", "aaa") returns 4

int count = 0;
int n = 0;

for (int i = 0; i >= str.length(); i++)
{
    if (word.equals(str.substring(count, count + n)))
    {
        count++;
    }
}
return count;

I think that simply looping and using startWith is a simpler solution

final String input = "baaaaaac";
final String find = "aaa";
int count = 0;
for (int i = 0; i < input.length() - find.length() + 1; i++) {
    if (input.substring(i).startsWith(find)) count++;
}
System.out.println(count);

Here is how you can do it without using the startsWith function by checking each possible consecutive phrase.:

public static int howManyWithOverlap(String sentence, String phrase){
    int length = sentence.length();
    int phraseLength = phrase.length();
    int count = 0;
    //Check each phrase of consecutive letters to see if it matches.

    for(int i = 0; i < length - phraseLength + 1; i++){
        if(sentence.substring(i, i + phraseLength).equals(phrase)){
            count++;
        }
    }

    //count is the number of instances in the sentence.
    return count;
}

This method should return the number of times that the phrase appears in the string. Now, all you have to do is call this function, howManyWithOverlap , and pass in your sentence, and then the phrase you are looking for. I hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM