在C++中,可以使用比较运算符(==、!=、<、>、<=、>=)来比较两个字符串指针。但是,这些运算符只比较字符串指针的地址,而不比较它们所指向的实际字符串内容。
为了比较两个字符串的实际内容,可以使用strcmp函数。strcmp函数接受两个字符串指针作为参数,并根据它们所指向的字符串内容进行比较。如果两个字符串相等,strcmp函数将返回0,否则将返回一个非0的值。
以下是一个使用strcmp函数比较两个字符串指针的示例代码:
#include
#include
using namespace std;
int main() {
char str1[] = "hello";
char str2[] = "world";
char* ptr1 = str1;
char* ptr2 = str2;
if(strcmp(ptr1, ptr2) == 0) {
cout << "str1 and str2 are equal" << endl;
} else {
cout << "str1 and str2 are not equal" << endl;
}
return 0;
}
在此示例中,我们比较了字符串指针ptr1和ptr2所指向的字符串内容。由于它们不相等,if语句将输出“str1 and str2 are not equal”。