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

前端 未结 5 557
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条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-18 15:48

    You don't need a fancy binary search to do the job. What you need is a double for loop that check for occurrence of each char in one string in another, and copy the non-occurring chars into a third char array (which is your result).

    Code can be something like the following (not tested!):

    char *s1, *s2, *result; /* original strings and the result string */
    int len1, len2; /* lengths of the strings */
    for (i = 0; i < len1; i++) {
       for (j = 0; j < len2; j++) {
         if (s1[i] == s2[j]) {
           break;
         }
       }
       if (j == len2) {  /* s1[i] is not found in s2 */
         *result = s1[i]; 
         result++; /* assuming your result array is long enough */
       }
    }
    

提交回复
热议问题