Share this page

# strncmp

String Manipulation Functions

Compares the first n characters of two strings.

    int strncmp( constchar *string1, const char *string2, size_t n );

string1 | The first string that is compared.
string2 | The second string that is compared.
n | The number of characters in each string that are compared.

## Return Values

Returns a value indicating the lexicographical relation between the strings:

Return value | Description
<0 | string1 is less than string2
0 | string1 is the same as string2
>0 | string1 is greater than string2

## Example

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

Tips to improve your search results... VuGen Function Reference Version 26.1 Function Reference 26.1 All View Local Help Center View Online Help Center Version: