C++ 字符串比较:strcmp 函数详解
在 C++ 中,可以使用 strcmp 函数来比较两个字符串是否相等。strcmp 函数是 C 语言标准库中的函数,可以在 C++ 中使用。
strcmp 函数的原型如下:
int strcmp(const char* str1, const char* str2);
该函数接受两个参数,分别是需要比较的两个字符串 str1 和 str2,并返回一个整数值。返回值为 0 表示两个字符串相等,返回值大于 0 表示 str1 大于 str2,返回值小于 0 表示 str1 小于 str2。
使用示例:
#include <iostream>
#include <cstring>
int main() {
const char* str1 = 'hello';
const char* str2 = 'world';
int result = strcmp(str1, str2);
if (result == 0) {
std::cout << 'str1 and str2 are equal' << std::endl;
} else if (result > 0) {
std::cout << 'str1 is greater than str2' << std::endl;
} else {
std::cout << 'str1 is less than str2' << std::endl;
}
return 0;
}
输出结果:
str1 is less than str2
需要注意的是,strcmp 函数比较的是两个 C 风格的字符串(以 null 结尾的字符数组),如果需要比较 C++ 的 std::string 对象,可以使用 std::string 类的 compare 函数。
原文地址: https://www.cveoy.top/t/topic/o2OZ 著作权归作者所有。请勿转载和采集!