2013-07-21 49 views
0

所以這裏的練習是設計一個程序,它接受一個字符串並刪除出現在第二個字符串中的字符串中的所有字符。所以對於我在下面選擇的字符串,其中第一個字符串是abc,第二個字符串是cde,我希望得到ab的輸出,而不是abcK&R練習擠壓功能

我已經看到一個非常簡潔的方法來做這個擠壓功能,只需要兩個簡單的循環,但我想知道爲什麼我長長的蜿蜒的方式不起作用。

#include<stdio.h> 

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'; 
} 

回答

2

在你的外部,而你應該重置「j」爲零。

如果「k」bekomes 1,那麼您不會再增加「i」。如果再次運行squeeze(),則不會再次初始化「k」。

從不使用全局變量(或模塊局部變量),如「k」。這會讓你的代碼不安全。

+1

+1爲'從不使用全局變量'的評論。它是一個輕微的過度陳述,但在這裏準確的'k'只在一個函數中使用。只有當需要從函數外部訪問時,才能在函數之外創建一個變量。 –

+0

好的,謝謝!順便說一句,我不增加「我」,因爲如果我已經'刪除'的字符,所以下一個字符是在陣列中的當前位置'我'。不是嗎? – MethequalsMath

1

高五 - 我也在閱讀那一章。我想我已經閱讀了大約4次,無論如何,我真的需要通過這樣做來學習,我會在幾個小時內忘掉所有內容。這就是爲什麼我幾乎完成了該章的所有練習 - 接下來的第3章!

這裏是我的解決方案 - 擠壓功能不符合getline函數兼容時(/0'迫使printf不打印到std出

彙編gcc 4.7.2

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

#include <stdio.h> 
#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'; 

    } 
} 

祝你好運!

+0

更加整潔的擠壓功能! :) – MethequalsMath