strcmp 是什么函数,如何使用?
strcmp 是 C/C++ 标准库中用于按字典序比较两个C风格字符串的函数,定义在
函数原型
int strcmp(const char* str1, const char* str2);
参数:两个以 \0 结尾的C字符串(const char* 类型)。返回值:
**< 0**:str1 小于 str2(按ASCII码逐字符比较,首个不同字符的差值)。**0**:两字符串完全相同。**> 0**:str1 大于 str2。
核心功能
区分大小写的比较
(例如 "Apple" 和 "apple" 会被认为不同)。逐字符比较ASCII值
从第一个字符开始逐个比较,直到遇到不同的字符或 \0。
使用示例
1. 基本比较
#include
#include
int main() {
const char* s1 = "apple";
const char* s2 = "banana";
int result = strcmp(s1, s2);
if (result < 0) {
std::cout << s1 << " < " << s2; // 输出:apple < banana
} else if (result > 0) {
std::cout << s1 << " > " << s2;
} else {
std::cout << s1 << " == " << s2;
}
return 0;
}
2. 检查字符串相等
if (strcmp(password, "secret123") == 0) {
printf("Access granted!\n");
}
3. 排序字符串数组
const char* fruits[] = {"banana", "apple", "cherry"};
int n = sizeof(fruits) / sizeof(fruits[0]);
// 按字典序排序(实际项目中建议用std::sort)
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (strcmp(fruits[i], fruits[j]) > 0) {
std::swap(fruits[i], fruits[j]);
}
}
}
// 结果:apple, banana, cherry
注意事项
非空终止字符串会导致未定义行为
char s1[3] = {'a', 'b', 'c'}; // 缺少\0
strcmp(s1, "abc"); // 危险!可能越界访问
C++中更安全的替代方案
优先使用 std::string 的 == 或 compare() 方法:
std::string s1 = "hello";
if (s1 == "world") { /*...*/ }
// 或
if (s1.compare("world") == 0) { /*...*/ }
非ASCII字符问题
对中文等非ASCII字符串,需使用本地化敏感的比较(如 strcoll)。
性能
时间复杂度为 O(n),需遍历字符串直到发现不同字符。
相关函数
函数描述strncmp比较前n个字符(避免越界)stricmp/strcasecmp不区分大小写的比较(非标准但广泛支持)memcmp比较内存块(可处理含\0的数据)
总结
何时用:需要快速比较C风格字符串时(如底层开发、嵌入式系统)。何时不用:在C++中优先选择 std::string,更安全且功能丰富。