gogoWebsite

C++ counts the number of times a character appears in a string

Updated to 14 hours ago
Question description

Enter a string s and a character ch, count and output the total number of times the character ch appears in the string s. Rewriting requirements: Write a function to find the number of times the character ch appears in the string pointed to by the character pointer p, and return the result as the function value. The function prototype is
int CountChar ( char* p, char ch ) ;

Enter a description

Enter a string and press Enter, and enter a character and then enter. (Tip: Use gets(s) to enter a string, s is the character array that stores the string)

Output description

The output is a positive integer, indicating the total number of times the character ch appears.

Enter sample
bb
a
Output sample
0
#include <iostream>
#include <cstdlib>

using namespace std;

int countchar(char *str,char a){
    int n = 0;
    int i = 0;
    
    while(*(str+i) != '\0'){
        if(*(str+i) == a){
        	n++;
		}
        i++;
    }
    return n;
}

int main() {
    char str[20], a;
    int n;
    
    gets(str);
    a = getchar();
    n = countchar(str,a);
    cout << n << endl;
}