Strings
We've made plenty of use of strings this semester. And, we've talked a little bit about them. But, going into the test, I want to look at them systematically and for the record. Unlike Java, the C Language has only a very minimal, second-class implementation of strings. In C, a string is really just an array of charactters. Consider the following example:
int index; char[] name = "George Washington"; for (index=0; index < 6; index++) { printf ("%c\n", name[index]); /* Prints G, e, o, r, g, e; one letter per line */ }One aspect of strings that is interesting is the way that C keeps track of the end of the string. Keep in mind that strings are represented as arrays, so, unlike Java, there is no size field. Instead, C annotes the end of the string within the string itself. It adds a NULL ('\0') at the end of each string. In the example above, althoguh the string "George" contains 6 letters, numbered 0 - 5, it actually is 7 characters long. The "invisible" 7th character is a null. The example below prints the numerical value of each character, including the 0-zero for the NULL:
int index; char[] name = "George"; for (index=0; index < 7; index++) { printf ("%d\n", (int) name[index]); /* Prints 71, 101, 111, ..., 0, one number per line */ }The null terminator can also be used to find the end of a string, as shown below:
int index; char[] name = "George"; char *cptr = name; while (cptr) { /* stops when cptr == 0 (NULL) */ printf ("%c\n", *cptr); /* Prints G, e, o, r, g, e; one number per line */ }The C Language has a ton of functions designed to make it easy to manipulate strings. You might want to take a look at the man pages associated with the following functions and give them a try:
- strcmp
- strncmp
- strcasecmp
- strncasecmp
- strcpy
- strncpy
- strdup
- strlen
- strtok
Test Review
The rest of class was spent reinforcing structs, pointers, arrays, the preprocessor, and other topics likely to make an appearance on Thursday's exam, which covers C-only (not shell or Perl).