C++ strcmp()

C++ 中的 strcmp() 函数用于比较两个以 null 结尾的字符串(C 字符串)。比较是按字典顺序进行的。它定义在 cstring 头文件中。

示例

#include <cstring>
#include <iostream>
using namespace std;

int main() {
  char str1[] = "Megadeth";
  char str2[] = "Metallica";

// compare str1 and str2 lexicographically int result = strcmp(str1, str2);
cout << result; return 0; } // Output: -1

strcmp() 语法

strcmp() 的语法是

strcmp(const char* lhs, const char* rhs);

这里,

  • lhs 代表左侧
  • rhs 代表右侧

strcmp() 参数

strcmp() 函数接受以下参数

  • lhs - 需要比较的 C 字符串的 指针
  • rhs - 需要比较的 C 字符串的指针

strcmp() 返回值

strcmp() 函数返回

  • 如果 lhs 中的第一个不同字符大于 rhs 中对应的字符,则返回一个正值
  • 如果 lhs 中的第一个不同字符小于 rhs 中对应的字符,则返回一个负值
  • 如果 lhsrhs 相等,则返回0

strcmp() 原型

strcmp()cstring 头文件中的定义原型是

int strcmp( const char* lhs, const char* rhs );
  • strcmp() 按字典顺序比较 lhsrhs 的内容。
  • 结果的符号取决于 lhsrhs 中第一个不同的字符对之间的差值。

strcmp() 未定义行为

如果以下任一情况,strcmp() 的行为是未定义的:

  • lhsrhs 中任意一个未指向 C 字符串(以 null 结尾的字符串)

示例 1: C++ strcmp()

#include <cstring>
#include <iostream>
using namespace std;

int main() {
  char str1[] = "Megadeth";
  char str2[] = "Metallica";

// returns -1 because "Megadeth" < "Metallica" lexicographically int result = strcmp(str1, str2);
cout << "Comparing " << str1 << " and " << str2 << ": " << result << endl;
// returns 1 because "Metallica" > "Megadeth" lexicographically result = strcmp(str2, str1);
cout << "Comparing " << str2 << " and " << str1 << ": " << result << endl;
// returns 1 because "Megadeth" = "Megadeth" lexicographically result = strcmp(str1, str1);
cout << "Comparing " << str1 << " and " << str1 << ": " << result; return 0; }

输出

Comparing Megadeth and Metallica: -1
Comparing Metallica and Megadeth: 1
Comparing Megadeth and Megadeth: 0

示例 2: 在用户定义函数中使用 strcmp()

#include <cstring>
#include <iostream>
using namespace std;

// function to display the result of strcmp()
void display(char *lhs, char *rhs) {

// compare display() parameters lhs and rhs int result = strcmp(lhs, rhs);
if (result > 0) cout << rhs << " precedes " << lhs << endl; else if (result < 0) cout << rhs << " follows " << lhs << endl; else cout << lhs << " and " << rhs << " are same" << endl; } int main() { char str1[] = "Armstrong"; char str2[] = "Army"; // lhs = str1, rhs = str2 display(str1, str2); // lhs = str2, rhs = str1 display(str2, str1); // lhs = str1, rhs = str1 display(str1, str1); // lhs = str2, rhs = str2 display(str2, str2); return 0; }

输出

Army follows Armstrong
Armstrong precedes Army
Armstrong and Armstrong are same
Army and Army are same

另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战