Example: strncmp

The following example compares two strings, string1 and string2, which are nearly identical except for the word, "the", in string1 and "one" in string2. strcmp returns an unequal comparison because it compares the whole string. strncmp compares 30 characters only in this example, which falls short of the word imbalance, and therefore returns an equal comparison.

    int result;
    char tmp[20];
    char string1[] = "The quick brown dog jumps over the lazy fox";
    char string2[] = "The quick brown dog jumps over one lazy fox";
// Perform a case sensitive comparison 
    result = strcmp(string1, string2); 
    if (result > 0)
        strcpy(tmp, "greater than");
    else if (result < 0)
        strcpy(tmp, "less than");
    else
        strcpy(tmp, "equal to");
    lr_output_message ("strcmp: String 1 is %s string 2", tmp );
// Compare 30 chars 
    result = strncmp( string1, string2 , 30); 
    if (result > 0 )
        strcpy(tmp, "greater than");
    else if (result < 0)
        strcpy(tmp, "less than"); 
    else
        strcpy(tmp, "equal to");
    lr_output_message ("strncmp: String 1 is %s string 2", tmp);
Example: Output:
Action.c(17): strcmp: String 1 is greater than string 2
Action.c(28): strncmp: String 1 is equal to string 2