C++ strncmp()

The strncmp() function in C++ compares a specified number of characters of two null terminating strings. The comparison is done lexicographically.

strncmp() prototype

int strncmp( const char* lhs, const char* rhs, size_t count );

The strncmp() function takes two arguments: lhs, rhs and count. It compares the contents of lhs and rhs lexicographically upto a maximum of count characters. The sign of the result is the sign of difference between the first pairs of characters that differ in lhs and rhs.

The behaviour of strncmp() is undefined if either of lhs or rhs do not point to null terminated strings.

It is defined in <cstring> header file.

strncmp() Parameters

  • lhs and rhs: Pointer to the null terminated strings to compare.
  • count: Maximum number of characters to compare.

strncmp() Return value

The strncmp() function returns a:

  • positive value if the first differing character in lhs is greater than the corresponding character in rhs.
  • negative value if the first differing character in lhs is less than the corresponding character in rhs.
  • 0​ if the first count characters of lhs and rhs are equal.

Example: How strncmp() function works

#include <cstring>
#include <iostream>

using namespace std;

void display(char *lhs, char *rhs, int result, int count)
{
    if(result > 0)
        cout << rhs << " precedes " << lhs << endl;
    else if (result < 0)
        cout << lhs << " precedes " << rhs << endl;
    else
        cout << "First " << count << " characters of " << lhs << " and " << rhs << " are same" << endl;
}

int main()
{
    char lhs[] = "Armstrong";
    char rhs[] = "Army";
    int result;

    result = strncmp(lhs,rhs,3);
    display(lhs,rhs,result,3);

    result = strncmp(lhs,rhs,4);
    display(lhs,rhs,result,4);

    return 0;
}

When you run the program, the output will be:

First 3 characters of Armstrong and Army are same
Armstrong precedes Army