C++中比较字符串主要有两种方法:①使用C风格的strcmp函数,需包含,通过返回值判断相等或大小;②使用std::string的比较运算符,需包含,语法更直观安全。
在C++中,比较两个字符串的方法主要有两种:使用C风格字符串的 strcmp 函数和C++标准库中 string 类型的比较运算符。它们的使用场景、语法和效率有所不同,下面详细对比说明。
strcmp 是C语言中的字符串比较函数,定义在
函数原型如下:
int strcmp(const char* str1, const char* str2);
返回值含义:
示例代码:
#include iostream>
#include
using namespace std;
int main() {
char str1[] = "apple";
char str2[] = "banana";
if (strcmp(str1, str2) == 0) {
cout
} else {
cout
}
return 0;
}
C++ 中的 std::string 类重载了比较运算符(如 ==、!=、 等),可以直接使用这些运算符进行字符串比较,更加直观和安全。
需要包含头文件
示例代码:
#include
#include
using namespace std;
int main() {
string s1 = "hello";
string s2 = "hello";
if (s1 == s2) {
cout
}
if (s1
cout
}
return 0;
}
基本上就这些。日常开发中优先使用 std::string 和其比较运算符,更简洁安全。只有在处理C接口或遗留代码时才需用 strcmp。