Archived

This topic is now archived and is closed to further replies.

dtmf2

returning all instances of a letter in a string

Recommended Posts

how could i code a function such as int countLetters(string inputString,string letter) that finds all instances of ''letter'' in ''inputSring'' and returns this? example: countLetters(ajajaja,a) returns 4

Share this post


Link to post
Share on other sites
STL is your friend

std::count(inputString.begin(), inputString.end(), letter);

count is in algorithm

letter is a char, instead of a string

Take care,
Bill




Edited by - Siebharinn on February 20, 2002 6:03:24 PM

Share this post


Link to post
Share on other sites
if you use char arrays (not STL strings):

int countLetter(char* daString, char daLetter)
{
int numLetters, strLength = strlen(daString);
for (int t = 0; t < strLength; ++t)
if (daString[t] == daLetter) ++numLetters;
return numLetters;
};


--- krez (krezisback@aol.com)

Share this post


Link to post
Share on other sites
the coolest part about the stl is that it works with built in arrays too!

int countLetter(char* daString, char daLetter)
{
int numLetters, strLength = strlen(daString);
return std::count(daString,daString+strLen,daLetter);

Share this post


Link to post
Share on other sites
quote:
Original post by sjelkjd
the coolest part about the stl is that it works with built in arrays too!

word?

WORD!

Share this post


Link to post
Share on other sites