[英]How to count words and punctuation in a string C program?
我正在尝试用C语言编写一个程序,该程序无需使用诸如数组之类的内置函数即可计算字符串中单词和标点符号的数量。 是否可以不使用数组呢? 另外,我当前的程序在下面,并且给我一个初始化* word的错误,但是我试图让用户输入一个字符串,然后程序对其进行计数,所以我不想初始化它。 非常感谢您的帮助!
#include <stdio.h>
#include<conio.h>
int main(){
char *word;
int countword = 0, i;
int countpunct = 0, i;
printf("\nEnter the String: ");
gets(word);
for (i = 0; word[i] == ' '; i++){
countword++;
}
for (i = 0; word[i] == '.' || '?' || '!' || '(' || ')' || '*' || '&'){
countpunct++;
}
printf("\nThe number of words is %d.", countword);
printf("\nThe number of punctuation marsks is %d.", countpunct);
getch();
}
一种方法是分别读取每个字符并进行处理。
#include <stdio.h>
#if 0
#include<conio.h>
#endif
int main(){
int word;
int countword = 0;
int countpunct = 0;
printf("\nEnter the String: ");
while ((word = getchar()) != EOF && word != '\n'){
if (word == ' ') countword++;
if (word == '.' || word == '?' || word == '!' || word == '(' || word == ')' || word == '*' || word == '&'){
countpunct++;
}
}
printf("\nThe number of words is %d.", countword);
printf("\nThe number of punctuation marsks is %d.", countpunct);
#if 0
getch();
#endif
}
有更多的代码行,但是switch
语句并不是一个坏方法。 下面的代码的一般思路应该起作用
#include <stdio.h>
#include <string.h> //for strlen()
int main(){
char input[255];
int wcount, pcount, i;
wcount = pcount = 0;
printf("\nEnter the String: ");
fgets(input, 255, stdin); //use this instead
for (i=0; i < strlen(input); i++){
switch (input[i]){
case ' ':
if (i > 0) wcount++;
break;
case '.':
case '?':
case '!':
case '(':
case ')':
case '*':
case '&':
pcount++;
break;
}
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.