문제
콘솔에서 사용자가 입력한 문자를 세는 프로그램을 작성하십시오. strlen() 함수를 사용하여 그 글자가 문장에서 몇 번이나 반복되는지 화면에 출력해야 합니다.
해결책
문자를 세는 데 사용한 논리는 다음과 같습니다. -
- 사용자에게 문장을 입력하도록 요청 런타임에.
printf("Enter a sentence\n");
gets(str); - 사용자에게 문자 를 입력하도록 요청 런타임에.
printf("Enter a character to check how many times it is repeating\n");
scanf("%c",&c); - 문장에서 문자를 세는 논리는 다음과 같습니다. -
for(i=0;i<strlen(str);i++){
if(str[i]==c){
count++;
}
} - 마지막으로 개수 인쇄
예시
다음은 한 문장에서 여러 번 반복되는 문자를 세는 C 프로그램입니다. -
#include<stdio.h>
#include<string.h>
main(){
int i,count=0;
char c,str[100];
printf("Enter a sentence\n");
gets(str);
printf("Enter a character to check how many times it is repeating\n");
scanf("%c",&c);
for(i=0;i<strlen(str);i++){
if(str[i]==c){
count++;
}
}
printf("Letter %c repeated %d times\n",c,count);
} 출력
위의 프로그램이 실행되면 다음과 같은 출력을 생성합니다 -
Enter a sentence Here are the C Programming question and answers Enter a character to check how many times it is repeating n Letter n repeated 4 times