there is number of way to do that.
you can use regex header file to do that. for validation exercise program this is a important header file.
see http://www.cplusplus.com/reference/regex/ for more info.
You could simply iterate through the string letter by letter and report the positions on the fly. Keep count of occurrences so you can report this at the end.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
void countGivenChar( const string& str, char givenChar )
{
unsigned count = 0;
for( unsigned i=0; i<str.size(); ++i )
{
if( str.at(i) == givenChar )// found one!
{
if( count == 0 ) cout << givenChar << " was found at position(s): ";// print this only once
cout << i << ' ';
++count;
}
}
if( count == 0 ) cout << "No " << givenChar << " was found.\n"
// add a line here to report how many times givenChar was found if count != 0.
}
Or, use the find() function to find them all, since one overload lets you specify the starting point in the string to search from: