------------------------------------------------------------------------------
MC logo
C String Facility
[^] Code Examples
------------------------------------------------------------------------------
<<C Strings str2.c String Copy Implementation I>>
/*
 * String games using the standard string facility.
 */
#include <stdio.h>
#include <string.h>

int main()
{
        char s1[25] = "This is the city.";
        char s2[50];
        char *p1, *p2;

        /* strcpy copies the second string to the first. */
        strcpy(s2, s1);
        printf("%s %s\n", s1, s2);

        /* Use strcat to add a second string to the first. */
        strcat(s2, "  Los Angeles, California.");
        printf("%s\n", s2);

        /* By fixing up the destination address, we can get strcpy to
           effectively cut off part of the first string. */
        strcpy(s2 + 7, "***");
        printf("%s\n\n", s2);

        /* The strlen function tells how many characters there are in the 
           string. */
        printf("\"%s\" has %d characters, \"%s\" has %d characters.\n\n",
               s1, strlen(s1), s2, strlen(s2));

        /* A strstr and strchr search for a substring or a member character. */
        p1 = strchr(s1, 'c');
        printf("[%c] [%s]\n", *p1, p1);
        p1 = strstr(s1, "the");
        printf("[%c] [%s]\n", *p1, p1);
        p2 = strstr(s1, "nope");
        if(p2 == NULL) printf("No \"nope\"\n");
        putchar('\n');

        /* This doesn't work correctly.  Java actually has a similar problem.
           It's annoying in C, but Java is s'posed to cleanup up stuff like
           that. */
        strcpy(s2, s1);
        printf("%s\n%s\n", s1, s2);
        if(s1 == s2)
                printf("Same.\n");
        else
                printf("Different.\n");

        /* You may use strcmp to compare strings. */
        if(strcmp(s1, s2) == 0)
                printf("Same.\n");
        else
                printf("Different.\n");
}

The strcmp function returns a value which indicates the result of comparing the two strings. It compares not only for equality, but for sorting order. The value of strcmp(s1, s2) is as follows:

When... Strcmp returns...
s1 < s2 A negative value
s1 == s2 Zero
s1 > s2 A positive value

This is not as peculiar as it looks. If you want to compare any two strings s1 and s2 with the operation °, where ° is one of ==, !=, <, >, <=, or >=, note that s1 ° s2 is equivalent to strcmp(s1,s2) ° 0. For instance, to test s1 <= s2, say strcmp(s1,s2) <= 0.

Reading: pp. 58-66
<<C Strings String Copy Implementation I>>