如何计算空白

时间:2014-09-28 09:50:48

标签: c

我一直在尝试计算句子中的空格量,但我不知道如何让程序知道我想要它计算哪个句子,请帮助我,这是我的代码。< / p>

#include <stdio.h>
#include <string.h>
#include <conio.h>

int wid, len, i, j, temp, blank;
char text[100], ch;

int main(){
printf ("Enter the width of the colum: ");
gets (text);
sscanf (text, "%d", &wid);
printf ("\nEnter a line of text: ");
gets (text);

len = strlen (text);
for (i = 0; i < 7; i++){
    printf ("1234567890");
}
while(len > 50){
    printf ("\nThe text is too long!\n");
    break;
}
ch = getch();
for (j = 0; j < len; j++){
    if (ch == ' ') {blank++;}
}
printf ("\n%d", blank);
}

我想计算这个部分有多少空白     printf(&#34; \ n输入一行文字:&#34;);     得到(文本);

2 个答案:

答案 0 :(得分:4)

而不是

ch = getch();
for (j = 0; j < len; j++){
if (ch == ' ') {blank++;}

尝试

for(j = 0; j < len; j++)
{
    if(text[j] == ' ') //comparing if the string in text contains blank space at position j
        blank++;
}

也可以使用fgets代替gets()来读取字符串。

答案 1 :(得分:0)

/* cprogram to count blanck spaces in the string*/
#include<stdio.h>
#include<string.h>
int main()
{
    int len,i,blank_space=0;
    char str[20];
    printf("Enter the string ");
    fgets(str,20,stdin);
    printf("%s",str);
    //claculate string length 
    len=strlen(str);
    //printing length of the string
    printf("length of the string is %d",len);
    //loop to detect blankspaces
    for(i=0;i<len;i++)
    {
        if(str[i]==' ')
        blank_space++;
    }
    //display the result
    printf("no of blanked spaces is %d",blank_space);
    return 0;

}