C++ `strcmp` Function: Compare Strings Easily

The strcmp function is a string comparison function in C/C++, used to compare the sizes of two strings. Its usage is as follows:

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

str1 and str2 are the two strings being compared, and the return value is an integer. The meaning of the return value is as follows:

  1. If the return value is 0, it means the two strings are equal.
  2. If the return value is less than 0, it means that str1 is less than str2.
  3. If the return value is greater than 0, it means that str1 is greater than str2.

Example:

“He has a lot of money”
– He is very wealthy.

#include <iostream>
#include <cstring>

int main() {
    const char* str1 = "abc";
    const char* str2 = "abd";
  
    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 << "两个字符串相等" << std::endl;
    }
  
    return 0;
}

Output result:

str1小于str2

There are a few key points to keep in mind when using the strcmp function:

  1. The strcmp function only compares the content of characters in strings, regardless of the length of the strings, so make sure that the strings passed in are terminated with a null character (‘\0’) to avoid potential memory access violations.
  2. The strcmp function is case-sensitive, meaning uppercase and lowercase letters are considered different characters. If case needs to be ignored, you can use the strcasecmp or stricmp function.
  3. It is recommended to use std::string and its related functions in C++ for string manipulation, instead of using C-style strings and strcmp function.
bannerAds