输入一个长度小于80的字符串,修改此字符串,将字符串中的字母字符滤掉掉,并统计新生成串中包含的字符个数。
#include <stdio.h>
int main(void)
{
char str[100];
int s;
printf("input a string:");
gets(str);
printf("The original string is :");
puts(str);
s = fun(str);
printf("The new string is :");
puts(str);
printf("There are %d char in the new string.\n",s);
return 0;
}
这是主函数,我改如何设计这个fun函数来达到我的期望
供参考:
#include <stdio.h>
#include <ctype.h>
int fun(char* s)
{
int len = 0;
char* p = s;
while (*p) {
if (!isalpha(*p)) {
*s++ = *p;
len++;
}
p++;
}
*s = '\0';
return len;
}
int main(void)
{
char str[100];
int s;
printf("input a string:");
gets(str);
printf("The original string is :");
puts(str);
s = fun(str);
printf("The new string is :");
puts(str);
printf("There are %d char in the new string.\n", s);
return 0;
}
一个实现供参考:
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int fun(char * str){
int i=0 ;
while(str[i]!='\0'){
while(isalpha(str[i])){ //如果遇到英文字母,则将后面的字符串往前一个位置,直到不是英文字母
strcpy(str+i,str+i+1);
}
i++;
}
return strlen(str);
}
int main(void)
{
char str[100];
int s;
printf("input a string:");
gets(str);
printf("The original string is :");
puts(str);
s = fun(str);
printf("The new string is :");
puts(str);
printf("There are %d char in the new string.\n",s);
return 0;
}