简体   繁体   中英

count number of non overlapping occurrences in a string

Hello i am trying to solve a problem where i count the number of non-overlapping occurrences of a string s2 in a string s1. Example String s1 = "abab" and String s2 = "ab" the number of occurrences is 2. Another example String s1 = "aaabbaa" and String s2 = "aa" the number of occurrences is 2. Final example if String s1 = "aabbaa" and String s2 = "AA" the number of occurrences equal 0. How would i go about the problem?

Idea: I know if i match the String s2 in s1. i move to the next position by adding the current index position with s2.length and if they are not equal increment the current index position by 1. My problem don't know how to start? How would you use iteration to solve this. Thanks for the help.

I hope this will be self-explanatory (using String.indexOf ):

public int countOccurrences(String haystack, String needle) {
  int count = 0, offset = 0, index;
  // As long as there is another occurrence...
  while((index = haystack.indexOf(needle, offset)) != -1) {
    // Skip already matched parts the next time
    offset = index + needle.length();
    // Increment counter
    count++;
  }
  return count;
}

Edit: @JennFitz requested a recursive version, so here it is (although the above method is much better):

public int countOccurrences(String haystack, String needle) {
  int index = haystack.indexOf(needle);
  if(index == -1) return 0;
  int offset = index + needle.length();
  return 1 + countOccurrences(haystack.substring(offset), needle);
}

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