K&R练习挤压function

所以这里的练习是设计一个程序,它接受一个字符串并删除该字符串中出现在第二个字符串中的所有字符。 因此,我在下面选择的字符串中,第一个字符串是abc,第二个字符串是cde,我想获得ab而不是abc的输出。

我已经看到了一个非常简洁的方法来做这个挤压function,只需要两个简单的for循环,但我想知道为什么我的长途跋涉方式不起作用。

 #include void squeeze(char s1[], char s2[]); void copy(char to[], char from[]); int k=0; main() { char array1[4]="abc"; char array2[4]="cde"; squeeze(array1, array2); printf("%s", array1); } void squeeze(char s1[], char s2[]) { int j,i,m; m=j=i=0; char s3[1000]; while(s1[i]!='\0') //What I'm doing here is taking a character in the string { //and comparing it with all characters in the second string. copy(s3,s1); //If it exists in the second string I'm 'deleting' that letter while(s2[j]!='\0') //from the first string. Then I start all over again with the { // next letter in line. Or at least that's the plan. if (s1[i]==s2[j]) { k=1; } ++j; } if (k==1) { m=i; while(s3[m+1]!='\0') { s1[m]=s3[m+1]; //I'm 'deleting' the letter by pushing each character ++m; //that is to the right of the deleted character to the } //left of the array. } if(k!=1) { ++i; } } s1[i]='\0'; } void copy(char to[], char from[]) { int i; i=0; while(from[i]!='\0') { to[i]= from[i]; ++i; } to[i]=='\0'; } 

在你的外部,你应该将“j”重置为零。

如果“k”bekomes 1,则不再增加“i”。 如果你第二次运行squeeze(),你不会再次初始化“k”。

永远不要使用全局变量(或模块局部变量),如“k”。 这使您的代码线程不安全。

高五 – 我也在阅读那一章。 我想我已经阅读了大约4次,无论如何我真的需要通过实践来学习,我会在几个小时内忘记所有内容。 这就是为什么我几乎完成了那一章的所有练习 – 第3章接下来!

这是我的解决方案 – 挤压function与getlinefunction不兼容( /0'强制printf不打印到标准输出。

gcc 4.7.2上编译

gcc -Wall -std=c99 -pedantic squeeze.c

 #include  #define LIM 100 void squeeze(char[], char[]); int ggetline(char[], int); int main() { //the getline function is buggy; it would produce null strings. char line1[LIM] = "hello"; char line2[LIM] = "hello2"; squeeze(line1, line2); printf("%s %s\n", line1, line2); return 0; } /* getline: reads line into s, returns length */ int ggetline(char s[], int lim) { int c, i; for (i = 0; i < lim-1 && (c = getchar()) != EOF && c!='\n'; ++i) s[i] = c; if (c == '\n') { s[i] = c; ++i; } s[i] = '\0'; return i; } void squeeze(char s1[], char s2[]) { int j, l, i, k; for (i = 0; s2[i] != '\0'; i++) { for (k = l = 0; s2[j] != '\0'; j++) { if (s1[j] != s2[i]) s1[k++] = s1[j]; } s2[k] = '\0'; } } 

祝好运!