【c++随笔26】char*、char[]比较是否相等
原创作者:郑同学的笔记
原文链接:https://zhengjunxue.blog.csdn.net/article/details/144634814
一、char*比较是否相等
1、是否可以使用==?
- char* 是指向字符数组(即字符串)的指针,而不是字符串本身。因此,使用 == 比较两个 char* 指针时,比较的是指针的值(即内存地址),而不是指向的字符串内容。
#include <iostream>
int main() {
const char* str1 = "hello";
const char* str2 = "hello";
const char* str3 = "world";
if (str1 == str2) {
std::cout << "str1 and str2 point to the same memory address." << std::endl;
} else {
std::cout << "str1 and str2 do not point to the same memory address." << std::endl;
}
if (str1 == str3) {
std::cout << "str1 and str3 point to the same memory address." << std::endl;
} else {
std::cout << "str1 and str3 do not point to the same memory address." << std::endl;
}
return 0;
}
结果:
str1 and str2 point to the same memory address.
str1 and str3 do not point to the same memory address.
在这个例子中,str1 和 str2 指向相同的字符串常量 “hello”,因此它们的内存地址相同,== 运算符返回 true。但是如果你将字符串常量 “hello” 拷贝到 str3 中,str1 和 str3 会指向不同的内存地址,即使它们表示的字符串内容相同。
2、正确的做法:使用 strcmp 比较字符串内容
- 如果你想比较两个 char* 指针指向的字符串内容是否相等,应该使用 std::strcmp 函数。std::strcmp 会逐个字符比较两个 C 风格字符串的内容。
使用 strcmp 进行字符串内容比较:
#include <iostream>
#include <cstring> // 引入 strcmp 函数
int main() {
const char* str1 = "hello";
const char* str2 = "hello";
const char* str3 = "world";
// 使用 strcmp 比较字符串内容
if (std::strcmp(str1, str2) == 0) {
std::cout << "str1 and str2 are equal." << std::endl;
} else {
std::cout << "str1 and str2 are not equal." << std::endl;
}
if (std::strcmp(str1, str3) == 0) {
std::cout << "str1 and str3 are equal." << std::endl;
} else {
std::cout << "str1 and str3 are not equal." << std::endl;
}
return 0;
}
str1 and str2 are equal.
str1 and str3 are not equal.
解释:
std::strcmp 比较两个 C 风格字符串的内容。如果它们相等,strcmp 返回 0,否则返回一个非零值。
strcmp 是按字符逐个比较字符串的内容,直到发现不同的字符或者遇到字符串结束符 \0。
总结:
- == 运算符:对于 char* 指针,== 比较的是指针的地址(内存位置),而不是指向的内容。
- 正确比较字符串内容:如果你想比较字符串的内容,应该使用 std::strcmp 函数。
二、char[]比较是否相等
- 在 C++ 中,判断 char[] 数组是否相等有一些特殊性,因为 char[] 是一个静态数组,不能直接使用 == 运算符来比较两个数组的内容。== 运算符对于数组来说,比较的是数组的内存地址,而不是数组的内容。
要比较两个 char[] 数组的内容,您可以使用 std::strcmp 函数(来自 头文件),它可以逐字符地比较两个 C 风格字符串(char[])的内容。
#include <iostream>
#include <cstring> // 引入 strcmp 函数
int main() {
// 定义两个 char 数组
char arr1[] = "hello";
char arr2[] = "hello";
char arr3[] = "world";
// 使用 std::strcmp 比较两个字符串
if (std::strcmp(arr1, arr2) == 0) {
std::cout << "arr1 and arr2 are equal." << std::endl;
} else {
std::cout << "arr1 and arr2 are not equal." << std::endl;
}
if (std::strcmp(arr1, arr3) == 0) {
std::cout << "arr1 and arr3 are equal." << std::endl;
} else {
std::cout << "arr1 and arr3 are not equal." << std::endl;
}
return 0;
}
arr1 and arr2 are equal.
arr1 and arr3 are not equal.