strcmp能比较string吗
时间: 2023-07-28 20:51:10 浏览: 42
strcmp函数是用于比较C语言中的字符串(char*)的,它不能直接比较C++中的string类型。在C++中,可以使用string类的成员函数compare进行字符串比较,或者直接使用运算符==进行比较。例如:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1 = "hello";
string str2 = "world";
if (str1.compare(str2) == 0) {
cout << "str1 and str2 are equal" << endl;
} else {
cout << "str1 and str2 are not equal" << endl;
}
if (str1 == str2) {
cout << "str1 and str2 are equal" << endl;
} else {
cout << "str1 and str2 are not equal" << endl;
}
return 0;
}
```
相关问题
strcmp 可以作用在string上吗
strcmp 函数是 C 语言中用于比较两个字符串的函数,它只能作用于 C 语言中的字符数组(即字符串)。而在 C++ 中,我们可以使用 std::string 类型来表示字符串,std::string 类型内部实现也是基于字符数组的,因此我们可以使用 string.c_str() 函数将 std::string 类型转换为 C 风格的字符串,然后再使用 strcmp 函数进行比较。例如:
```
#include <iostream>
#include <cstring>
#include <string>
int main() {
std::string str1 = "hello";
std::string str2 = "world";
if (strcmp(str1.c_str(), str2.c_str()) == 0) {
std::cout << "str1 and str2 are equal" << std::endl;
} else {
std::cout << "str1 and str2 are not equal" << std::endl;
}
return 0;
}
```
上面的代码中,我们先定义了两个 std::string 类型的字符串 str1 和 str2,然后使用 strcmp 函数比较它们是否相等。注意,我们需要使用 string.c_str() 函数将 std::string 类型转换为 C 风格的字符串。
string strcmp
strcmp是C语言中的一个函数,用于比较两个字符串的大小。它接受两个参数,即要比较的两个字符串。如果第一个字符串小于第二个字符串,则返回一个负数;如果第一个字符串大于第二个字符串,则返回一个正数;如果两个字符串相等,则返回0。
以下是一个使用strcmp函数的示例:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1<span class="em">1</span><span class="em">2</span><span class="em">3</span><span class="em">4</span>