Count occurrences of a sub string in a String

Viewed 118

First of all, I know there are many duplicates of this question but I have tried and tried and non have been able to solve my issue.

I have the following string

string s = "asdfqasdfp";

I need to loop through the string and find which sub string appears more than once. so in this case its

asdf

I have made the following code but I do not know why it doesn't work. I start from the full string and go down one at a time. I should get occurence value of 2.

int t = s.length();
for (int i = 0; i < s.length(); i++) {
    string str = s.substr(0, t);
    int occurence = 0;
    size_t start = 0;
        while ((start = s.find(str, start)) != string::npos) {
            ++occurence;
            start += str.length();
        }
        if (occurence > 1) {
            cout << occurence;
        }
        else {
            --t;
        }
    }

EDIT: I only want the largest substring that the string contains, in this case

"asdf"

2 Answers

Here's a fixed version of your code, including Daniel's suggestions (thanks! Daniel's demo)

for (size_t t = s.length(); t >= 1; --t) {
    for (size_t i = 0; (i + t) <= s.length(); i++) {
        std::string str = s.substr(i, t);
        size_t occurence = 0;
        size_t start = 0;
        while ((start = s.find(str, start)) != std::string::npos) {
            ++occurence;
            start += str.length();
        }
        if (occurence > 1) {
            std::cout << str << " " << occurence << std::endl;
            return 0;
        }
    }
}

You need to

  1. loop over t, and decrement it at the end of the i loop rather than inside
  2. limit i to s.length() - t, so that there's always a t-length string to take as str
  3. fix your substr to start at i not 0

You can also stop at the first time you find a duplicate, since this will be a largest duplicate (e.g. if there are two pairs of duplicates of length 4 it will find one of them, but it doesn't sound like you need both). You should also use size_t throughout as your integer type since that's what's used by the string functions here.

Looks ok. Do you need an << endl; to see output in your terminal?

Related