How do I complete K&R Exercise 2-4?

前端 未结 5 540
Happy的楠姐
Happy的楠姐 2020-12-18 14:49

I\'m learning how to write programs in C using the k&r book (The C Programming Language) and I have a problem with one of the exercises. It\'s asking me to detect and re

5条回答
  •  Happy的楠姐
    2020-12-18 15:28

    A binary search is way overkill for this. You need three indices. One index (i) to walk through s, one index (k) to walk through t, and one index (j) to keep track of where you are in s for the characters that you need to keep because they are not in t. So, for each character in s, check and see if it is in t. If it is not, keep it in s.

    void squeeze(char *s, char *t) {
        int i, j, k;
        int found = 0;
    
        for(i = j = 0; s[i] != '\0'; i++) {
            found = 0;
            for(k = 0; t[k] != '\0' && (found == 0); k++) {
                if(t[k] == s[i]) {
                    found = 1;
                }
            }
    
            if(found == 0) {
                s[j++] = s[i];
            }
    
        }
    
        s[j] = '\0';
    }
    

提交回复
热议问题