C June 16, 2009
I’ve decided that I want to learn C instead of Haskell and Python now and am using the book to learn from. I gotta say, I’m very impressed with K&R2. Absolutely great. The best part about the book is that it contains many exercises at the end of each section which gives you practice writing C programs. I just finished the 2-4 exercises and it was quite a challenge for some reason. The problem was to write a function that takes two strings and remembers the characters in one string from the other. I thought it’s worth posting my solution. I’m not sure how ‘good’ my style is, but I’m following my style from K&R so it can’t be very bad…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | #include <stdio.h> void squeeze(char[], char[]); main() { char s1[] = "Hello, world!"; char s2[] = "Hlo"; squeeze(s1, s2); printf("%s\n", s1); } /* squeeze: deletes all characters in s2 from s1 */ void squeeze(char s1[], char s2[]) { int i, j, k; for(i = j = 0; s1[i] != '\0'; i++) { int found = 0; for(k = 0; s2[k] != '\0'; k++) { if(s1[i] == s2[k]) { found = 1; } } if(!found) { s1[j++] = s1[i]; } } s1[j] = '\0'; } |
The stuff in the main is just some testing that I did. From what I can tell, it seems to work as expected. Yay C!
Leave a Reply