Just start at the beginning of the string and go through each character, testing for the key each time. If the two characters match then replace the one in the string with an asterisk and increment a counter:
Code:
#include <iostream>
#include <string>
int searchString ( std::string& searchIn, const char searchWith )
{
int occurances = 0;
for ( int i = 0; i < searchIn.length(); i++ ) {
if ( searchWith == searchIn[i] ) {
occurances++;
searchIn[i] = '*';
}
}
return occurances;
}
int main()
{
char searchKey;
std::string userInput;
std::cout<<"Enter a string: ";
std::getline ( std::cin, userInput );
std::cout<<"Enter a character to search for: ";
std::cin>>searchKey;
std::cout<<"There were "<< searchString ( userInput, searchKey )
<<" occurances of "<< searchKey <<'\n';
std::cout<<"Modified String: "<< userInput <<'\n';
return 0;
}
-Prelude