String Functions

The string library contains a number of functions for manipulating strings. To use these functions, you must include the library in your code as follows:

#include <string.h>


	strcpy(char * destination, const char * source);
The function strcpy will copy the source string to the destination string. Whatever content is in the destination string will be replaced by the source string. For example,
    char str[32];
    strcpy(str, "happy");
    //the string str now equals "happy"
There is another functions:
	strncpy(char * destination, const char * source, int n);
which will copy n characters of the source string to the destination string.


	strcat(char * destination, const char * source);
The function strcat concatenates the source string to the destination string. In other words, it adds the source string to the end of the destination string. Continuing our example:
    strcat(str, " birthday!");
    //the string str is now "happy birthday!"


	strcmp(const char * string1, const char * string2);
strcmp compares two strings. If the strings are equal it returns 0. If string1 is alpahbetically ahead of string2, it returns a negative number. If string2 is alphabetically ahead of string1, it returns a positive number.


	strlen(char * string);
The function strlen or string length returns the number of characters in the string. The termination character '\0' is not included in this count.

There are other functions in the string library, but these are the ones you are most likely to need.

Finally, it should be noted that since a string is just an array, it can be manipulated using index notation. For instance in our example, str[2] is equal to 'p'. Also, values in the string can be changed:

    str[1] = 'i';
    str[2] = 'l';
    str[3] = 'l';

    //str is now equal to "hilly birthday!"

next


 home                      table of contents                      about