题目描述
给定一个由英文字符、数字、空格和英文标点符号组成的字符串,长度不超过2000,请将其切分为单词,要求去掉所有的非英文字母,每行输出一个单词。
例如有文本:Python was created in 1990 by Guido van Rossum at Stichting Mathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands.
处理完成之后得到以下单词:
Python
was
created
in
by
Guido
van
Rossum
at
Stichting
Mathematisch
Centrum
CWI
see
http
www
cwi
nl
in
the
Netherlands
问题:在编程训练系统中测评完成率只有10%,我在VS上运行时得出的结果是正常的,想知道是哪里出的问题。********
我的代码:
#include"stdio.h"
int hanshu(char ch)
{
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
{
return 1;
}
else
{
return 0;
}
}
int main()
{
char ch[2000];
fgets(ch, 2000, stdin);
int i = 0;
int flag = 0;
int f = 1;
while (ch[i] != '\n')
{
if (hanshu(ch[i])==1)
{
printf("%c", ch[i]);
f = 0;
}
else if(f==0&&hanshu(ch[i])==0)
{
flag = 1;
}
if (flag == 1 && f == 0)
{
if (ch[i + 1] != '\n')
{
printf("\n");
flag = 0;
f = 1;
}
}
i++;
}
return 0;
}
正确答案
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
int h=0,i;
char ch[2000];
gets(ch);
for(i=0;ch[i]!='\0';i++){
if((ch[i]>='a'&&ch[i]<='z')||(ch[i]>='A'&&ch[i]<='Z'))
{
if(h!=0)
{
printf("\n");
h=0;
}
printf("%c",ch[i]);
}
else
{
h++;
}
}
return 0;
}
1.长度不超过2000 定义数组长度的时候 是不是应该还要算上 '\n' 和 '\0'字符的长度呢 多设置一点也没关系吧 数组长度修改为2048
2.检测下一个字符非字母时35行不用判断了吧 因为当前字符ch[i]已经不是字母了有可能就是'\n',整个字符串到i已经结束了 再判断ch[i+1]就不对了吧,再说前面调用hanshu的时候已经筛选了'\n',后面不需要判断