0

my problem is that my code used to find patterns in words find "pattern" letter by letter. (My goal is to use my code to find whole patterns in one word, for example, for word "abcabcabc" and pattern "abc" i would like to achive result of "3".)

There is my code

   case 2:{
            string text, pattern;
            int a, b;
            int counter = 0;
            cin >> text >> pattern;

            for (a = 0; a < text.size(); a++) {
                for (b = 0; b < pattern.size(); b++) {
                    if (text[a] == pattern[b])
                        counter++;
                }
            }
            cout << counter;
            break;
         }
mvjkel_
  • 1
  • 1
  • Check this link if its helpful- [https://www.techiedelight.com/count-number-times-pattern-appears-given-string-subsequence/](https://www.techiedelight.com/count-number-times-pattern-appears-given-string-subsequence/) – Shadab Hussain Mar 19 '20 at 21:49
  • From earlier today [How do I check if a pattern exists in an entered string?](https://stackoverflow.com/q/60763235/3422102) - C, but on point.Or simply use [std::basic_string::find](https://en.cppreference.com/w/cpp/string/basic_string/find) – David C. Rankin Mar 19 '20 at 22:00
  • @DavidC.Rankin the question is asking about the count of patterns, so string::find won't work. – cigien Mar 19 '20 at 22:04
  • Sure it will, it returns the `index` to the start of the patter, so you just keep an offset and work down the string. – David C. Rankin Mar 19 '20 at 22:09
  • 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) – cigien Mar 19 '20 at 22:14
  • @DavidC.Rankin Aah I see, I thought you meant in a single call. – cigien Mar 19 '20 at 22:15
  • Yes, kinda like this one [Number of vowels in string of characters C++](https://stackoverflow.com/questions/54613617/number-of-vowels-in-string-of-characters-c/54614087?r=SearchResults&s=8|19.3807#54614087) – David C. Rankin Mar 19 '20 at 22:17

1 Answers1

0

There are two well known general purpose algorithms:
Knuth–Morris–Pratt algorithm
Boyer–Moore

If you need something more special, Wikipedia might help to find a direction where to start:
(String matching algorithms)[https://en.wikipedia.org/wiki/Category:String_matching_algorithms]

schnedan
  • 234
  • 1
  • 9