0

The following assignment is presented:

Given a string of characters. Calculate how many times “ABBA” is used in it.

My code:

#include<iostream>
#include<string>
using namespace std;
int main()
{
    string aBBa = "Abbakiy Abbakum Abbak'evich";
    int i = 0, j = 0;

    cout << "Expression: " << aBBa << endl;
    do {
        if (aBBa[i] == 'а')
            j++;
        i++;
    } while (aBBa[i] != '\0');
    cout << "Quantity letters a: " << j << endl;
    i = 0;
    system("pause");
    return 0;
}

I was only able to understand how to find the number of letters in the text, if I try to find it half-word in the same way (namely, in the fragment below I will write instead of a - abba),

if (aBBa[i] == 'а')
                j++;

then the program will refuse to calculate anything (the value will be zero).

Example

Anatoly
  • 3
  • 5
  • 2
    Why you just do not use `std::string::find()` ? – Slava Nov 20 '19 at 18:57
  • Or `strpos`... or any number of other options. – 3Dave Nov 20 '19 at 19:05
  • Would the correct result count overlapping occurences like `"ABBABBA"` als two (because two can be found within the text) or as one (because if one ABBA is removed from the text, none is remaining)? – grek40 Nov 20 '19 at 21:20
  • 1
    Get rid of the `system("pause");`. You have no idea what the `pause` command does on my computer. For all you know, it might pause the cooling system on my home nuclear reactor. Using it prevents the program from being used in a pipeline. See [system(“pause”); - Why is it wrong?](https://stackoverflow.com/questions/1107705/systempause-why-is-it-wrong) for more. – David Schwartz Nov 20 '19 at 22:33
  • In addition to @DavidSchwartz 's comment, instead of the `system("pause")"`, find out how to make your Windows IDE stop closing the console window when the program exits, so that the output may be examined. – Kaz Nov 20 '19 at 22:45

1 Answers1

0
#include<iostream>
#include<string>

int main()
{
    std::string needle = "Abba";
    std::string haystack = "Abbakiy Abbakum Abbak'evich";
    int i = 0, j = 0, count = 0;

    std::cout << "Expression: " << haystack << std::endl;
    do {
        if (haystack[i] == needle[j])
        {
            j++;
            if (j == needle.size())
            {
                ++count;
                j = 0;
            }
        }
        else
           j = 0;
        i++;
    } while (haystack[i] != '\0');
    std::cout << "Needles in the haystack: " << count << std::endl;
    return 0;
}

There are several questions that explain why using namespace std; and system("pause"); are harmful. Don't use them.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278