求一个字符串中空格字符的个数。
一行字符,前、后及中间有数量不定的空格。
例子输入: three !
例子输出:4
[解决办法]
int count_non_empty(iostream &os = cin)
{
int count = 0;
char c;
while(c = os.getchar)
{
if(c == ' ')
{
++count;
}
return count;
}
[解决办法]
- C/C++ code
#include<iostream>using namespace std;int count_non_empty(char* p){ int count = 0; while(*p != '\0') { if(*p == ' ') { ++count; } p++; } return count;}int main(){ char a[32]={0};int b; gets(a); b=count_non_empty(a); cout<<b; return 0;}
[解决办法]
[解决办法]
这个我写的,包你行
#include <iostream>
using namespace std;
int main(void)
{
char ch[100];
printf("Input a string:");
cin.getline(ch,100);
int len;
len = strlen(ch);
int spaceNum = 0;
for (int i = 0; i < len; i++)
{
if (ch[i] == ' ')
{
spaceNum++;
}
}
printf("\nYou input: %s\n", ch);
printf("Total number of space is: %d\n", spaceNum);
system("pause"); // 暂停程序
return 0;
}