乐闻世界logo
搜索文章和话题

How to use the strcmp function in C++?

1个答案

1

In C++, the strcmp function is used to compare whether two strings are equal. It is part of the C standard library, so when using it in C++ programs, you need to include the header file <cstring>.

The prototype of the strcmp function is defined as follows:

cpp
int strcmp(const char *s1, const char *s2);

Here, s1 and s2 are pointers to the two strings to be compared. The return value is an integer indicating the result of the comparison:

  • If the return value is 0, the two strings are equal.
  • If the return value is less than 0, the first string s1 is lexicographically less than the second string s2.
  • If the return value is greater than 0, the first string s1 is lexicographically greater than the second string s2.

Example Code

cpp
#include <iostream> #include <cstring> // Include the header file for strcmp int main() { const char *str1 = "Hello"; const char *str2 = "World"; const char *str3 = "Hello"; // Compare str1 and str2 if (strcmp(str1, str2) == 0) { std::cout << "str1 and str2 are the same string" << std::endl; } else { std::cout << "str1 and str2 are different strings" << std::endl; } // Compare str1 and str3 if (strcmp(str1, str3) == 0) { std::cout << "str1 and str3 are the same string" << std::endl; } else { std::cout << "str1 and str3 are different strings" << std::endl; } return 0; }

In this example, strcmp is used to compare two sets of strings. The first comparison between str1 and str2 outputs that they are different. The second comparison between str1 and str3 outputs that they are the same.

This function is useful for implementing lexicographical string sorting or validating string content when processing user input. Note that using strcmp requires ensuring that the input strings are valid and null-terminated (with the null character '\0'), otherwise it may lead to undefined behavior.

2024年7月24日 09:26 回复

你的答案