c - 如何找出用户输入在 C 中的时间长度?
问题描述
#include <stdlib.h>
int main(){
int sum=1;
char sent[50];
fgets(sent, sizeof(sent), stdin);
for(int i=0;i<=strlen(sent);i++){
if(i==' '){
sum++;
}
}
scanf("%s", sum);
return 0;
}
我想要的是找出句子中有多少个单词。我怎样才能知道句子有多长?提前致谢。
解决方案
继续@chux 的伪代码,实现将是:
#include <stdio.h>
#include <ctype.h>
#define MAXS 50 /* if you need a constant, #define one (or more) */
int main (void){
int sum = 0, i = 0, inword = 0; /* use inword as a flag, in/out word */
char sent[MAXS];
if (fgets(sent, sizeof(sent), stdin) == NULL) { /* read/VALIDATE input */
fputs ("(user canceled input)\n", stderr);
return 1;
}
while (sent[i]) { /* loop over each character */
if (isspace(sent[i])) { /* is the character a space? */
inword = 0; /* set flag to false */
}
else { /* otherwise */
if (!inword) /* if we were reading spaces, now in word */
sum += 1; /* increment sum */
inword = 1; /* set flag true */
}
i++; /* increment loop counter */
}
printf ("whitespace separated words: %d\n", sum);
}
您保留一个“状态”变量inword
,该变量跟踪您是否“在一个单词中”读取字符,或者在读取空格的单词之前、之间或之后的状态。这也确保忽略前导空格、多重包含空格和尾随空格。
推荐阅读
- c - 结构看不到指针?
- android - 在选择器 StateListDrawable 中使用 attr 引用
- javascript - 如何使用单独的模板文件构建简单的 Vue.js 应用程序?
- python - 在散景中通过 CustomJS 触发 HoverTool 工具提示的显示
- kotlin - Kotlin 测试,如何使用 DescribeSpec 测试样式运行 BeforeEach
- javascript - V-Select 在一次选择中显示整个阵列
- r - 在使用多个模式时找出匹配的模式
- python - 我想检查 html 文本作为条件,但我应该如何处理 &nsbp 或?
- scala - 在兄弟 Actor 之间路由时在 Akka 中遇到死信
- javascript - 通过拖放更改ul li的顺序