Archived

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

returning all instances of a letter in a string

This topic is 5780 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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