ANSWERS TO EXERCISES ON STRINGS
1. The point of this exercise is that characters are represented as integers
in C. The actual values depend on the system; in ASCII, 65 represents
the character 'A', and 48 represents the character '0'.
'A' : A 65
'8' : 8 56
66 : B 66
'A' + 2 : C 67
n = 528
2. They all do.
(a) string library function, K+R page 250
(b) K+R page 39
(c) i isn't used until after the statement anyway
(d) K+R page 99
(e) Sedgewick, page 114
(f) Sedgewick, page 114
(g) K+R page 103
3. Can't increment array name. Have to copy into pointer as in 2 (d).
Note also that this program assumes the input is 100 characters
or less. You can use scanf("%100s", a) to ensure this. Remember,
one extra character is needed for '\0'.
4. Prints out all the words in the standard input whose characters appear
in decreasing order.
% a.out
my wife tried dancing the polka but everyone laughed
4 wife
5 tried
3 the
5 polka
% a.out < /usr/dict/words | grep 6
6 sponge
% a.out < ~cs126/files/wordlist.txt | grep 7
7 sponged
7 wronged
/usr/dict/words and ~cs126/files/wordlist.txt are files containing
lists of English words. The Unix command 'grep 6 filename' prints all
lines in the file that contain '6'.
5. Replace the for loop in the program of exercise 3 with
for (i = 0; i < N; i++)
if (word[i] != word[N-1-i])
break;
This solution is twice as slow as it could be: we could stop the
for loop in the middle. Exercise: fix the program to do so.
% a.out
ifihadahifi
11 ifihadahifi
% a.out < ~cs126/files/wordlist.txt | grep 7
7 deedeed
7 murdrum
7 repaper
7 reviver
7 rotator
7 sooloos
6. void remove_duplicates(char word[]) {
int i, j;
char prev = '\0';
for (i = j = 0; word[i] != '\0'; i++) {
if (prev != word[i])
word[j++] = word[i];
prev = word[i];
}
word[j] = '\0';
}
7. (a) #include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#define MAX_LEN 10000
int main(int argc, char *argv[]) {
int c, i;
char a[MAX_LEN + 1];
FILE *filename = fopen(argv[1], "r");
if(filename == NULL) {
printf("Error opening file.\n");
exit(EXIT_FAILURE);
}
i = 0;
while ((c = getc(filename)) != EOF)
a[i++] = c;
a[i] = '\0';
fclose(filename);
printf("%s\n", a);
return 0;
}
(b) Modify the while loop as follows.
while ((c = getc(filename)) != EOF)
if (c == 'a' || c == 'c' || c == 'g' || c == 't')
a[i++];
(c) Modify the while loop as follows. Be sure to #include <ctype.h>
for the isupper() function.
while ((c = getc(filename)) != EOF)
if (isupper(c) && c != 'Z')
a[i++];