C++ strcmp: Compare String Size Guide

In C++, you can use the strcmp function to compare the size of two strings. This function is a standard library function in C and is used to compare whether two strings are equal or their size relationship.

The prototype of the strcmp function is as follows:

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

The function takes two parameters, which are the two strings str1 and str2 to be compared. It returns an integer value indicating the relationship in size between the two strings.

When the return value is 0, it means that str1 is equal to str2;
When the return value is less than 0, it means that str1 is less than str2;
When the return value is greater than 0, it means that str1 is greater than str2.

Here is an example code that compares string sizes using the strcmp function.

#include <iostream>
#include <cstring>

int main() {
    const char* str1 = "abc";
    const char* str2 = "def";

    int result = strcmp(str1, str2);

    if (result == 0) {
        std::cout << "str1和str2相等" << std::endl;
    } else if (result < 0) {
        std::cout << "str1小于str2" << std::endl;
    } else {
        std::cout << "str1大于str2" << std::endl;
    }

    return 0;
}

In the above example, we compared the sizes of two strings “abc” and “def” by calling the strcmp function. Since “abc” is smaller than “def”, the final output is “str1 is less than str2”.

bannerAds