关于C#:计算一个单词中的字母数和句子中的单词数
To count the number of letters in a word and no of words in a sentence
我只是想尝试计算一个单词中的字母数。为了区分字符串中的单词,我正在检查空格。如果遇到空格,那么它是一个单词并且它有各自的字母。
例如"你好世界"。所以输出应该像
|
1
2 3 |
o/p
Hello has 5 letters World has 5 letter |
但是当我尝试编写代码时,我遇到了分段错误。下面是代码。
|
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
#include <stdio.h>
#include <string.h> main(void) { int nc = 0; char str[] ="This test"; } printf("%d } |
相关讨论
- 查看 isspace(str)。我想你的意思是 str[i]
- isspace(str)?这看起来很糟糕......你为什么不使用i? 🙂
- 另外,isspace() 不是需要 #include <ctype.h> 吗?
- 您可能想阅读例如这个 isspace 参考。
首先,在您的代码中添加 #include <ctype.h>。
接下来,isspace() 接收一个 int 参数并检查输入 [根据 ASCII 值] 是否为
white-space characters. In the"C" and"POSIX" locales, these are: space, form-feed ('\f'), newline ('
'), carriage return ('
'), horizontal tab ('\t'), and vertical tab ('\v').
因此,您需要将数组str 的元素一一提供给isspace()。为此,您需要将代码更改为
|
1
|
if(isspace(str[i]))
|
如果 str[i] 是空白字符,则将给出非零值。
此外,为了匹配您所需的输出 [如问题中所述],您需要使用 str[i] 的中间值并在 isspace() 的每个 TRUE 值之后重置 nc。
试试这个..
|
1
2 3 4 5 6 7 8 9 10 11 12 13 14 |
for(i = 0; i < len; i++)
{ if(isspace(str[i])) { ++word; continue; } ++nc; } if(len>0) word++; printf("%d %d |
相关讨论
- \'words\'的个数没有定义为"空格个数1"。
- 字数为(空格数1)。是不是?
- 没有。" counterexample"、" counter example"、"counter ### example"(其中#代表一个空格)。不过没有汗水,这是一件小事,因为您的代码纠正了 OP 做错了什么。
- 你是对的..但我认为他只考虑积极的部分。 "反例"
在开头加上#include <ctype.h>得到isspace()的原型,
|
1
|
if(isspace(str))
|
应该是
|
1
|
if(isspace(str[i]))
|
相关讨论
- 嗨 timrau 感谢您的快速回复。它现在正在工作。但是你能告诉我那里出了什么问题吗?
像这样改变条件。
|
1
|
if(isspace(str[i]))
|
因为 isspace 是 int isspace(int c);
试试看
|
1
2 3 4 5 6 7 8 9 10 11 12 13 |
int len = strlen(str); //len will be number of letters
for(int i = 0; i < len; i++) { if(isspace(str[i])) ++word; } if(len){ |
当你得到 len 时,它会给你字母的数量,所以不需要计算 nc。
|
1
|
int isspace(int c);
|
这是isspace()函数的原型。
您需要传递要检查的值,例如:
|
1
|
isspace(str[i]);
|
不是整个字符串。