问答题
1. 请编写一个函数,用来删除字符串中的所有空格。
例如,输入“abe de f gh”,则输出为“abcdefgh”。
注意:部分源程序如下。
请勿改动main()函数和其他函数中的任何内容,仅在函数proc()的花括号中填入所编写的若干语句。
试题程序:
#include<stdio.h>
#include<ctype.h>
#include<conio.h>
#include<stdlib.h>
void proc(char *str)
{
}
void main()
{
char str[81];
system("CLS");
printf("Input a string:");
gets(str);
puts(str);
proc(str);
printf("***str:%s\n",str);
}
【正确答案】int proc(char *str)
{
int i,j=0;
for(i=0;str[i]!='\0';i++) //从下标为0开始判断
if(str[i]!='') //当其不为空格时,把其放到str数组中
str[j++]=str[i];
str[j]='\0'; //最后用'\0'作为结束标志
}
【答案解析】 题目要求删除字符串中的所有空格,这需要检查字符串中的每一个字符。将不是空格的字符放入原来的字符串中,形成新的字符串。在新的字符串的末尾加上结束符。