0

Expected Outcomes: Enter two strings: abababab bab The occurrence of bab in abababab is: 3 I have tried it, but something wrong in my code, idk what. Here is it:

#include <iostream>
#include <string>
using namespace std;

int occurence(string s1, string s2) {
    int count,k;
    string x;
    for (int i = 0; i < s1.length(); i++)
    {
        k = 0;
        for (int j = 0; j < s2.length(); j++) {
            x[j] = s1[i];
        }
        for (int z = 0; z < s2.length(); z++) {
            if (s2[z] == x[z]) {
                k++;
            }
        }
        if (k == s2.length()) {
            count++
        }
    }
    return count;
}

int main() {
    cout << "Enter two strings: ";
    string w1, w2;
    cin >> w1 >> w2;
    int occur=occurence(w1,w2);
    cout << "The occurrence of " << w2 << " in " << w1 << " is " << occur;
}
kadyr
  • 1
  • 1
  • *Something is wrong* is not enough of a problem description. I'm guessing your problem stems from the line `x[j] = s1[i];`. You are trying to access elements of an empty string, which is UB. c++ doesn't do bounds checking for you when using `operator[]`, try `x.at(j) = s1[i]` and it will probably throw an out-of-bounds exception. – super Jan 15 '21 at 09:50
  • 2
    Does this answer your question? [Counting the number of occurrences of a string within a string](https://stackoverflow.com/questions/22489073/counting-the-number-of-occurrences-of-a-string-within-a-string) – Deumaudit Jan 15 '21 at 09:59
  • why at all this temporary string x is needed? can't you just use std::string::find() is a loop until it returns std::string::npos, and if occurrence found, restart search at the next position, if it ensures enough characters to fit the string you are searching for? Not submitting you complete code but explaining idea, the rest is your homework :) – ivan.ukr Jan 15 '21 at 10:14
  • why do you think there is something wrong? Please include example input, output and expected output to the question – 463035818_is_not_an_ai Jan 15 '21 at 10:18

0 Answers0