Re: Stroustrup 5.9 exercise 12
On Apr 10, 12:17 pm, "Daniel T." <danie...@earthlink.net> wrote:
"arnuld" <geek.arn...@gmail.com> wrote:
i am not able to come up with any solution for this. i am not even
able to think of one line of code for this solution.
/* Strouostrup, 5.9, exercise 12
* STATEMENT:
* write a function that counts the number of occurrences of a pair of
* letters ina "string" and another that does the same in a zero-
terminated
* array fo char(a C style string). e.g. the pair "ab" appears twice in
* "xabaacbaxabb"
*/
#include<iostream>
#include<string>
int main()
{
std::string s, pair;
std::cout << "Enter a word: ";
std::cin >> s;
std::cout << "Enter a pair of letters or a single letter you want to
find in the word: ";
std::cin >> pair;
// that's ALL i can think of
1) search for the first character in the pair,
2) check if the character after it is the second one of the pair,
3) search for the next character of the pair.
4) goto 2
Why 3?
This is basically just searching for a substring or a pattern;
the fact that the search string is always two characters is
really irrelevant. There are many algorithms for doing this
more or less rapidly over a very large string, but the classic
solution uses nested tests; you write a function which says
whether you have a match at the current position, call it, then
advance. Searching for the first character separately may be a
valid optimization, if searching for a single character is
particularly rapid. Searching for the last character can be
even faster, because depending on the character that you
actually find there, you may be able to jump more than a single
character ahead (BM search). But I rather think that that's
getting ahead of the original poster.
Of course, in modern C++, you don't write such things, because
there are already standard library functions available which do
it for you. I *don't* think it's the goal of the exercises, and
as a learning experience, I think that the original poster
should write the code without using such functions, but he might
also want to look into std::string::find or std::search.
And while I'm at it, I might note that the specification is
ambiguous. How many times does "aa" occur in "baaab"? Before
I'd write one line of code, I'd clarify this point. For the
exercise, it really doesn't matter. But it's important to write
code against a rigorous requirements specification, so that you
can know whether it works or not.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34