Yêu cầu:
- Viết hàm đếm số lần xuất hiện kí tự c trong chuỗi s
Giải thuật:
- Duyệt chuỗi kí tự và so sánh với kí tự c
Code:
/*******The number of character occurrence in s*************/
#include <conio.h>
#include <stdio.h>int cntChar(const char* s, char c);
void main()
{
char s[] = "ngoton blog for every one";
char c = 'o';
printf("The number of \'%c\' = %d", c, cntChar(s, c));
getch();
}
/*********************************************
Function : cntChar()
Parameter: [IN] s: string
[IN] c: characeter
Return : the number of occurrence of c in s
**********************************************/
int cntChar(const char* s, char c)
{
int idx, cnt = 0;
for (idx = 0; s[idx] != NULL; idx++)
{
if (s[idx] == c)
{
cnt++;
}
}
return cnt;
}
Kết quả:
1 |
The number of 'o' = 5 |
Leave a Reply