[英]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.