10. Strings


A string is a theoretical construct in modern physics that is used to help explain the very fabric of the universe itself.

This is exactly the same as a C string, except that it is, in fact, completely different.

A string in C is a sequence of bytes in memory that usually contains a bunch of letters. Constant strings in C are surrounded by double quotes ("). You may have seen strings before in such programming blockbusters, such as Hello World:

#include <stdio.h>

int main(void)
{
    printf("Hello, World!\n");

    return 0;
}

You've spotted the string "Hello, World!\n" in there, haven't you.

What type is that string, anyway? Well, it turns out that a constant string (that is, one in double quotes) is of type char*. But you can also put a string in a char array, if you so desire. The char* points at the first character in the string. Examples:

char *s = "Hello!";

printf("%s\n", s);    /* prints "Hello!" */
printf("%c\n", *s);   /* prints 'H' */
printf("%c\n", s[0]); /* prints 'H' */
printf("%c\n", s[1]); /* prints 'e' */
printf("%c\n", s[4]); /* prints 'o' */

(Note the two new format specifiers for printf() here: %c for printing a single char, and %s for printing a string! Ain't that exciting!)

And look here, we're accessing this string in a whole variety of different ways. We're printing the whole thing, and we're printing single characters.

You can also initialize char arrays during their definition, just like other arrays:

char s[20] = "The aliens are coming!";

And you can change the array elements on the fly, too by simply assigning into it:

char s[20] = "Give me $10!";

printf("%s\n", s);  /* prints "Give me $10!" */

s[9] = '8';
printf("%s\n", s);  /* prints "Give me $80!" */

In this case, note that we've put a constant char on the right side of the assignment. Constant chars use the single quote (').

One more thing to remember is that when you specify an array by name without the square brackets, it's just like using a pointer to the beginning of the array. So you can actually do assignments like this:

char a[20] = "Cats are better.";
char *p;

p = a;  /* p now points to the first char in array a */

One more thing: strings in C end with a NUL character. That is, a zero. It is most properly written as '\0', You can truncate a string to zero length by assigning '\0' to the first byte in the string. Also, all the standard string functions assume the string ends with a NUL character.

Standard string functions, did I say? Yes, I did.

C provides a whole metric slew of functions that you can use to modify strings, stick them together, parse them apart, and so on. Check out the reference section for all the brilliant string processing power at your disposal. It is your responsibility as a citizen of the Planet Earth to wield this ultimate power wisely! (And pay me $80.)