在C++里,strcmp是用来比较C风格字符串(也就是以空字符结尾的字符数组)的函数。它不属于string类,而是定义在cstring头文件中的标准库函数。通过strcmp,我们可以判断两个字符串是否相等,或者谁排在前面。

strcmp的基本用法
函数原型如下:
#include <cstring> int strcmp(const char* str1, const char* str2);
它会逐字符比较str1和str2,直到遇到不同的字符或者遇到结束符 。返回值规则是:
- 返回0:两个字符串完全相等
- 返回小于0的值:str1小于str2
- 返回大于0的值:str1大于str2
简单示例代码
下面演示如何比较两个字符数组:
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char a[] = "apple";
char b[] = "banana";
// 比较a和b
int result = strcmp(a, b);
if (result == 0) {
cout << "字符串相等" << endl;
} else if (result < 0) {
cout << "a小于b" << endl;
} else {
cout << "a大于b" << endl;
}
return 0;
}
常见错误和注意点
不要比较string对象
strcmp只接受const char*类型的参数。如果传入C++的string对象,需要先用c_str()方法转换:
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
int main() {
string s1 = "hello";
string s2 = "world";
// 正确做法:使用c_str()
int r = strcmp(s1.c_str(), s2.c_str());
cout << r << endl;
return 0;
}
确保字符串合法
如果传入未初始化的指针或者不是以 结尾的字符数组,strcmp会继续向后读内存,导致未定义行为。因此一定要保证参数是正常的C风格字符串。
和关系运算符的区别
用==比较两个字符数组名,实际上比较的是指针地址,而不是内容。例如下面的写法是错误的:
char a[] = "abc";
char b[] = "abc";
if (a == b) { // 错误:比较的是地址
// 不会按内容相等进入
}
只有使用strcmp才能按内容比较。如果是C++的string类型,则可以直接用==,因为string类重载了运算符。
小结
strcmp是处理C风格字符串比较的基础函数。记住包含cstring、传入合法字符数组、根据返回值判断结果,就能在C++中稳定地使用它完成字符串比较任务。