Problem With Deleting characters from string (C)

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • hennessy
    New Member
    • Feb 2011
    • 1

    Problem With Deleting characters from string (C)

    Hello all, this is my first time on bytes and i was wondering if anyone could give me a hand with my program. I have written a program that, when given an input of 2 words, removes all the letters from the first word that are in the second word. For example, if it is given the words "Hello World", it removes letters from the first word, "Hello" if they occur in the second, "World", leaving the letters "Hel". For some reason, however, it is not 100% accurate. When i enter "Hello World" it outputs "Helo". Often there are one or two letters left in the output that should not be there. I was hoping someone could point out where im going wrong.
    Here is the code:
    Code:
    int main (void){
        char x[20];
        char y[20];
        int i, j;
        scanf("%[a-z] %[a-z]", x, y);
        for(i=0; i < strlen(x); i++){
          for(j = 0; j < strlen(y); j++){
               if(x[i] == y[i]){
                x[i] = -1;
                  break;
                     }
                  }
                }
        for(i = 0, j = 0; i < strlen(y); i++){
              if(x[i] != -1){
               x[j] = x[i];
               j++;       
                      }
              }
        x[j] = '\0';
        printf("%s", x);
        getch();
        return 0;
        }
    I would really appreciate it if someone could get back to me. Cheers.
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    Have you stepped though the code using your debugger?

    I suspect a logic fault. That is, you need to build an array of letters from the first word as a first step. The word Hello would produce the array Helo. Next, start with the second word and pass that letter against youe array If you find it, then tou delete it in the string by doing a strcpy(n, n+1). This will shift the string to the left. No examine the letter in position n again. Repeat until you reach the null terminator.

    Use a small string to start nad build u a series of test cases in increasing difficulty.

    Comment

    • Savage
      Recognized Expert Top Contributor
      • Feb 2007
      • 1759

      #3
      Code:
            for(j = 0; j < strlen(y); j++){
                 if(x[i] == y[i]){ // x[i] == y[j], instead
                  x[i] = -1;
                    break;
                       }
                    }
                  }
      Think that should be it.

      Savage

      Comment

      Working...