Archive

Posts Tagged ‘strcmp’

C Strings

March 1st, 2010 No comments

First and most important of all regarding C strings is this: there is no such thing as C strings.

OK, now that that’s out of the way we can move on. The way to work with strings in C is to treat them as simple sequences of characters, a.k.a. a string in C is stored as an array of char’s. To know where the string ends, it must be terminated by a special marker, which is the ASCII character with the code 0 (commonly known as ‘\0′) – this is why they’re called zero-terminated C strings (we’ll see later that there are alternatives to this). Let’s see an example:

char myString[100];

myString[0] = 'h';
myString[1] = 'e';
myString[2] = 'l';
myString[3] = 'l';
myString[4] = 'o';
myString[5] = '\0'; /* don't forget the marker */

If you want to do the memory allocation stuff by hand, you would just change the declaration for myString to this:

char *myString = NULL;
myString = (char *)malloc(100 * sizeof(char));

Just creating a string and putting some characters inside isn’t such a big deal. You have to be able to do all sorts of stuff with it for this to be useful, things like copy them around, splitting them up (getting sub-strings from a bigger string), putting them back together (concatenating two strings into a single one), searching for things inside them. Fortunately, the creators of the C standard library thought of us and provided functions that do all of these things and more. All you have to do to use them is:

#include <string.h>

We’ll look in detail at some of these functions and, in the spirit of learning by doing, we’ll also try to provide our own implementations for them. Read more…