strncmp() function in C++

In this guide, you will learn what is strncmp() function is in C++ programming and how to use it with an example.

1. strncmp() Function Overview

The strncmp() function is part of the <cstring> library in C++ and is used to compare a specified number of characters from two C-style strings. It returns an integer that provides information about the relationship between the substrings.

Signature:

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

Parameters:

- str1: The first string to be compared.

- str2: The second string to be compared.

- num: Number of characters to compare.

2. Source Code Example

#include <iostream>
#include <cstring>

int main() {
    char string1[] = "applepie";
    char string2[] = "applejack";
    size_t lengthToCompare = 5;

    // Compare the first five characters of string1 and string2
    int result = strncmp(string1, string2, lengthToCompare);
    if(result == 0) {
        std::cout << "The first " << lengthToCompare << " characters of both strings are the same." << std::endl;
    } else if(result < 0) {
        std::cout << "The first " << lengthToCompare << " characters of string1 are less than those of string2." << std::endl;
    } else {
        std::cout << "The first " << lengthToCompare << " characters of string1 are greater than those of string2." << std::endl;
    }

    return 0;
}

Output:

The first 5 characters of both strings are the same.

3. Explanation

1. The <iostream> header is included for standard input/output, and <cstring> is included to use strncmp().

2. Two strings, string1 and string2, are initialized.

3. We defined lengthToCompare as 5, which indicates the number of characters we want to compare.

4. Using strncmp(), the first five characters of string1 and string2 are compared.

5. Based on the result, appropriate messages are printed to the console.

The strncmp() function provides flexibility in string comparison as it allows users to specify how many characters they want to compare. This can be useful in scenarios where only a subset of a string needs to be checked, such as file extensions, prefixes, etc.


Comments