|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
统计一行文本的单词个数
本题目要求编写程序统计一行字符中单词的个数。所谓“单词”是指连续不含空格的字符串,各单词之间用空格分隔,空格数可以是多个。
输入格式:
输入给出一行字符。
输出格式:
在一行中输出单词个数。
输入样例:
Let's go to room 209.
输出样例:
5
我的代码:
#include <stdio.h>
#include <string.h>
char jump()
{
char c;
while((c=getchar()==' '))
return c;
}
int main()
{
int c=0,cn=0;
char ch,c1;
ch=getchar();
if(ch==' ')
c1=jump();
if(c1=='\n')
printf("0");
else{
do
{
ch=getchar();
if(ch==' ')
{
c++;
c1=jump();
ch=c1;
}
}while(ch!='\n');
c++;
}
printf("%d\n",c);
return 0;
}
错误点:
测试点0
sample等价,有标点,词间空1格
答案正确
测试点1
多个空格,长、短字符串
答案错误
测试点2
空格结尾
答案错误
测试点3
1个最短单词,前有空格
答案正确
测试点4
全空格
答案错误
思路不是很清晰,题意也不太理解。
本帖最后由 bin554385863 于 2019-12-9 05:15 编辑
- #include <stdio.h>
- #include <string.h>
- int func(const char *str)
- {
- int c = 1;
- char cstr[strlen(str)+1];
- strcpy(cstr, str);
- for (char *i = cstr; *(i + 1) != '\0'; i++)
- {
- if (*i != ' ' && *(i+1) == ' ')
- {
- c++;
- }
- }
- if(cstr[strlen(cstr) - 1] == ' ')
- {
- c = c - 1;
- }
- return c;
- }
- int main(int argc, char const *argv[])
- {
- char *cstr = "Let's go to room 209.";
- printf("%d", func(cstr));
- return 0;
- }
复制代码
====================================================
Microsoft Windows [版本 10.0.18363.476]
(c) 2019 Microsoft Corporation。保留所有权利。
E:\Users\admin\Documents\VScode\Code>c:\Users\admin\.vscode\extensions\ms-vscode.cpptools-0.26.2\debugAdapters\bin\WindowsDebugLauncher.exe --stdin=Microsoft-MIEngine-In-hlrzprod.hg0 --stdout=Microsoft-MIEngine-Out-di1cm5cx.s1c --stderr=Microsoft-MIEngine-Error-s1vkov2d.qbw --pid=Microsoft-MIEngine-Pid-hmybkx1g.hrq --dbgExe=D:\MinGW\bin\gdb.exe --interpreter=mi
5
E:\Users\admin\Documents\VScode\Code>
|
|