在 C 语言中,可以使用标准库函数
strcmp
来比较两个字符串是否相等。
例如:
#include <string.h>
int main() {
char str1[] = "hello";
char str2[] = "hello";
if (strcmp(str1, str2) == 0) {
printf("The two strings are equal.\n");
} else {
printf("The two strings are not equal.\n");
}
return 0;
}
上面的代码将输出 “The two strings are equal.”。
注意,
strcmp
函数只能用于比较两个 null-terminated 的字符串,也就是以 null 字符结尾的字符串。如果要比较两个字符数组,可以使用
memcmp
函数。
另外,在 C++ 中,可以使用 std::string 类型来表示字符串,它提供了许多方便的操作,包括比较两个 std::string 对象是否相等。例如:
#include <string>
#include <iostream>
int main() {
std::string str1 = "hello";
std::string str2 = "hello";
if (str1 == str2) {
std::cout << "The two strings are equal." << std::endl;
} else {
std::cout << "The two strings are not equal." << std::endl;
}
return 0;
}
这段代码也将输出 “The two strings are equal.”。
版权声明:本文为weixin_35751194原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。