[英]i want to count words but it is not counting the word once it is appeared in the sentence
[英]To count the number of letters in a word and no of words in a sentence
我只是想嘗試計算單詞中字母的數量。為了區分字符串中的單詞,我正在檢查空格。如果遇到空格,則它是一個單詞並且具有各自的字母。 例如“ Hello World”。 所以輸出應該像
o/p
Hello has 5 letters
World has 5 letter
但是,當我嘗試編寫代碼時,出現了細分錯誤。 下面是代碼。
#include <stdio.h>
#include <string.h>
main(void) {
int nc = 0;
int word = 0;
char str[] = "This test";
int len = strlen(str);
int i;
for(i = 0; i < len; i++)
{
++nc;
if(isspace(str)){
++word;
}
}
printf("%d\n",nc);
}
在開頭添加#include <ctype.h>
以獲得isspace()
的原型,然后
if(isspace(str))
應該
if(isspace(str[i]))
嘗試這個..
for(i = 0; i < len; i++)
{
if(isspace(str[i]))
{
++word;
continue;
}
++nc;
}
if(len>0) word++;
printf("%d %d\n",nc, word);
首先,在代碼中添加#include <ctype.h>
。
接下來, isspace()
一個int
參數,並檢查輸入(以ASCII值表示)為
空格字符。 在“ C”和“ POSIX”語言環境中,這些是:空格,換頁('\\ f'),換行('\\ n'),回車('\\ r'),水平制表符('\\ t' )和垂直標簽('\\ v')。
因此,您需要將數組str
的元素一對一地提供給isspace()
。 為此,您需要將代碼更改為
if(isspace(str[i]))
如果str[i]
是空白字符,它將給出非零值。
另外,為了匹配所需的輸出(如問題中所述),您需要使用str[i]
的中間值,並在isspace()
每個TRUE
值之后重置nc
。
像這樣改變條件。
if(isspace(str[i]))
因為isspace是int isspace(int c);
int isspace(int c);
這是isspace()
函數的原型。
您需要像這樣傳遞您要檢查的值:
isspace(str[i]);
不是整個字符串。
試試看
int len = strlen(str); //len will be number of letters
for(int i = 0; i < len; i++)
{
if(isspace(str[i]))
++word;
}
if(len){
//if you dont want to count space letters then write
//len -= word;
word++; //counting last word
}
printf("letters = %d, Words =%d", len,word);
當您獲得len
,它將為您提供字母數,因此無需計算nc
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.