strcmp() function in C++

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

1. strcmp() Function Overview

The strcmp() function is used to compare two C-style strings. This function is part of the <cstring> library in C++. It returns an integer that indicates the relationship between the strings.

Signature:

int strcmp(const char* str1, const char* str2);

Parameters:

- str1: The first string to be compared.

- str2: The second string to be compared.

2. Source Code Example

#include <iostream>
#include <cstring>

int main() {
    char string1[] = "apple";
    char string2[] = "orange";
    char string3[] = "apple";

    // Compare string1 and string2
    int result1 = strcmp(string1, string2);
    std::cout << "Comparison between apple and orange: " << result1 << std::endl;

    // Compare string1 and string3
    int result2 = strcmp(string1, string3);
    std::cout << "Comparison between apple and apple: " << result2 << std::endl;

    return 0;
}

Output:

Comparison between apple and orange: -1
Comparison between apple and apple: 0

3. Explanation

1. We included the <iostream> header for standard input/output and <cstring> for using strcmp().

2. Three strings string1, string2, and string3 are initialized.

3. strcmp() is used to compare string1 with string2 and string1 with string3.

4. The result of the comparison is stored in result1 and result2.

5. The comparison results are printed to the console.

The strcmp() function provides a way to compare two strings lexicographically. If the strings are equal, it returns 0. If the first string is lexicographically less than the second, it returns a negative number; otherwise, it returns a positive number.


Comments