You are on page 1of 2

***************UNANG SOLUSYON*************

#include <iostream>
#include <cctype> //imports character functions
#include <cstring> //imports string functions
#include <cstdlib>
using namespace std;
//prototype function
int count(const char * const str, char a);
int main()
{
//initialize the string
char string[80];
//declare the character variable
char ch;
//prompt user to enter a character
cout << "Enter a character: ";
cin >> ch;
//prompt user to enter a string
cout << "Enter a string: ";
cin >> string;
//invoke the function
count(string, ch);
//pause & display screen
system("PAUSE");
return 0;
}
int count(const char * const str, char a)
{
//Find the number of occurences of a in str begins
int countOccur = 0;
for (int i = 0; str[i] != '\0'; i++)
if (str[i] == a)
countOccur++;
//find the number of occurrence of c in str end
cout << "Number of occurrences of " << a << " in " << str << " = " << countOccur
<< endl;
//return the count
return countOccur;
}
**********************PANGALAWANG SOLUSYON*******************
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int count(const char * const, char);
int main(int argc, char *argv[]) {
string s;
char c;
cout << "Enter a string : ";
getline(cin,s);
cout << "Enter a char : ";
cin >> c;
cout << "Number of occurrences of '" << c;
cout << "' in \"" << s << "\" = ";
cout << count(s.c_str(),c) << endl;
return 0;
}
int count(const char * const str, char a) {
int n = 0;
const char *p = reinterpret_cast<const char *>(str);
while ((p = strchr(p,a)) != NULL) {
++p;
++n;
}
return n;
}

You might also like