Afficher un message
Vieux 27/02/2008, 10h52   #4
James Kanze
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Beginners: Count occurrences of a string within a string

On Feb 27, 4:37 am, yogi_bear_79 <yogi_bear...@yahoo.com> wrote:
> I'm sure I have a few things wrong here. But I am stuck on
> how to do a recurring search. Also my statement cin >> quote;
> acts weird. If I enter more than one word it blows right past
> cin >> findMe; and completes and exits the code. If you
> string for cin >> quote; is one word it behaves correctly or
> at least in that regard!


So how do you want to decide how much text to read with the
first >>. If you want a word (skipping any white space which
precedes it), use >>. If you want a line, use getline(). If
you want the entire file, you can do so using
istreambuf_iterators, or with something like s <<
std::cin.rdbuf(), where s is a istringstream, but then you'll
have read end of file, and not be able to enter the search
string. If you want some other convention, you'll probably have
to program it. (Under Unix, a line consisting of a single '.'
is a frequent convention. This could be done something like:

std::string line ;
while ( std::getline( std::cin, line ) && line != "." ) {
quote += line + '\n' ;
}

. I'd definitely put this in a separate function, however.)

For the lookup, I'd generally prefer the standard algorithms
over the member functions of std::string. If you're learning,
I'd especially prefer them; they represent the usual idiom for
processing any container, and using them will get you used to
iterators in general. Something like:

int
countMatches(
std::string const& text,
std::string const& toMatch )
{
int result = 0 ;
for ( std::string::const_iterator current
= std::search( text.begin(), text.end(),
toMatch.begin(),
toMatch.end() ) ;
current != text.end() ;
current = std::search(
current + toMatch.size(), text.end(),
toMatch.begin(), toMatch.end() ) {
++ result ;
}
return result ;
}

--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
  Réponse avec citation
 
Page generated in 0,05228 seconds with 9 queries