Example of strncmp()

C++




// C, C++ program to demonstrate
// functionality of strncmp()
 
#include <cstring>
#include <iostream>
using namespace std;
 
int main()
{
    // Take any two strings
    char str1[10] = "akash";
    char str2[10] = "aksh";
 
    // Compare strings using strncmp()
    int result = strncmp(str1, str2, 4);
 
    if (result == 0) {
        // num is the 3rd parameter of strncmp() function
        cout << "str1 is equal to str2 up to num characters"
             << endl;
    }
    else if (result > 0)
        cout << "str1 is greater than str2" << endl;
    else
        cout << "str2 is greater than str1" << endl;
 
    cout << "Value returned by strncmp() is: " << result
         << endl;
 
    return 0;
}


Output

The first 5 characters are same.

std::strncmp() in C++

std::strncmp() function in C++ lexicographically compares not more than count characters from the two null-terminated strings and returns an integer based on the outcome. This function is a Standard Library function that is defined in <cstring> header file in C++.

Similar Reads

Syntax

int strncmp(const char *str1, const char *str2, size_t count);...

Example of strncmp()

C++ // C, C++ program to demonstrate // functionality of strncmp()   #include #include using namespace std;   int main() {     // Take any two strings     char str1[10] = "akash";     char str2[10] = "aksh";       // Compare strings using strncmp()     int result = strncmp(str1, str2, 4);       if (result == 0) {         // num is the 3rd parameter of strncmp() function         cout << "str1 is equal to str2 up to num characters"              << endl;     }     else if (result > 0)         cout << "str1 is greater than str2" << endl;     else         cout << "str2 is greater than str1" << endl;       cout << "Value returned by strncmp() is: " << result          << endl;       return 0; }...

What does strcmp() function return?

...

Important Points

When the strings are not equal, the value returned by the strncmp() function is the difference between the ASCII values of the first unmatched character in str1 and str2....

Contact Us