题目:
重新编写squeeze(s1, s2),将字符串s1中任何与字符串s2中字符匹配的字符都删除。
自我解答:
#include#define MAXSIZE 1000 char news1[MAXSIZE]; void squeeze(const char s1[], const char s2[]) { int i = 0; int j = 0; int k = 0; bool findc = false; while(s1[i] != ' ') { j = 0; while(s2[j] != ' ') { if(s1[i] == s2[j]) findc = true; j++; } if(!findc) news1[k++] = s1[i]; else findc = false; i++; } news1[k] = ' '; } int main() { squeeze("abcdef", "ab"); printf("%sn", news1); squeeze("abcdef", ""); printf("%sn", news1); squeeze("abcdef", "aab"); printf("%sn", news1); squeeze("abcdef", "abcdefgh"); printf("%sn", news1); }
运行结果:
cdef abcdef cdef
参考答案:
#includevoid squeeze(char s1[], char s2[]) { int i, j, k; for(i = k = 0; s1[i] != ' '; i++) { for(j = 0; s2[j] != ' ' && s2[j] != s1[i]; j++) ; if(s2[j] == ' ') s1[k++] = s1[i]; } s1[k] = ' '; }
这个函数的第一条语句
for(i = k = 0; s1[i] != ' '; i++)
对整型变量i和k、字符数组s1的下标以及结果字符串(也就是s1)分别进行了初始化。字符串s1中与字符串s2中的字符相匹配的字符都将被删除。整个循环语句将一直执行到字符串s1结束为止。
第二条for语句将s1[i]与s2中的每个字符相比较。这个循环将执行到字符串s2结束或者找到一个匹配字符为止。如果没有找到匹配的字符,s1[i]就将被复制到结果字符串中。如果找到了匹配的字符,语句 if(s2[j] == '0')中的条件表达式的求值结果将是假,s1[i]就不会被复制到结果字符串中(它将从字符串s1中被剔除出去)。
补充:
使用下面代码进行测试:
int main()
{
char s1[] = "abcdef";
char s2[] = "ab";
squeeze(s1, s2);
printf("%sn", s1);
char s3[] = "abcdef";
char s4[] = "";
squeeze(s3, s4);
printf("%sn", s3);
char s5[] = "abcdef";
char s6[] = "aab";
squeeze(s5, s6);
printf("%sn", s5);
char s7[] = "abcdef";
char s8[] = "abcdefg";
squeeze(s7, s8);
printf("%sn", s7);
}
测试结果为:
cdef abcdef cdef
注1. 参考答案的实现是覆盖了原有的字符串,而自我实现中定义了一个全局变量用于存储新的字符串。
注2.自我实现中的测试代码不能用于参考答案中,否则会导致程序的崩溃,因为字符串常量不能被改变。



