std::strncmp

Header: <cstring>

Compares at most count characters of two possibly null-terminated arrays. The comparison is done lexicographically. Characters following the null character are not compared.

# Declarations

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

# Parameters

# Return value

Negative value if lhs appears before rhs in lexicographical order.

# Notes

This function is not locale-sensitive, unlike std::strcoll and std::strxfrm.

# Example

#include <cstring>
#include <iostream>
 
void demo(const char* lhs, const char* rhs, int sz)
{
    const int rc = std::strncmp(lhs, rhs, sz);
    if (rc < 0)
        std::cout << "First " << sz << " chars of ["
                  << lhs << "] precede [" << rhs << "]\n";
    else if (rc > 0)
        std::cout << "First " << sz << " chars of ["
                  << lhs << "] follow [" << rhs << "]\n";
    else
        std::cout << "First " << sz << " chars of ["
                  << lhs << "] equal [" << rhs << "]\n";
}
 
int main()
{
    demo("Hello, world!", "Hello, everybody!", 13);
    demo("Hello, everybody!", "Hello, world!", 13);
    demo("Hello, everybody!", "Hello, world!", 7);
    demo("Hello, everybody!" + 12, "Hello, somebody!" + 11, 5);
}

# See also