C++中的字符串比较——字符数组、字符串(类)、字符指针

xiaoxiao2021-03-01  12

正如在C++中可以用3种方法(字符数组、字符串(类)、字符指针)访问一个字符串,比较字符串(内容)自然也有这三种基本形式。废话不多说,上代码,一看便知:

#include <iostream> #include <string.h> using namespace std; int main() { char str1[] = "abc"; char str2[] = "abc"; string str3 = "abc"; string str4 = "abc"; const char* str5 = "abc";//指向字符串的字符指针str5 const char* str6 = "abc";//指向字符串的字符指针str6 // 1、 字符数组——比较字符串 // str1、str2是字符数组中str1[0]、str2[0]的地址 cout << (str1 == &str1[0]) << endl;//结果是true,输出1 cout << (str1 == str2) << endl;// 结果是false,输出0 // 正确比较字符数组中的字符串是否一样,可以使用strcmp函数,一样则返回0 if(0 == strcmp(str1,str2)) cout<< "str1 = str2 : true" << endl << endl; else cout<< "str1 = str2 : false" <<endl << endl; // 2、字符串string(类)——比较字符串 // 字符串string(类)间比较字符串内容直接使用关系运算符(==、>、<、>=、<=)即可 cout << (str3 == str4) << endl;//结果是true,输出1 cout << (str3 >= str4) << endl<< endl;//结果是true,输出1 // 3、指向字符串的字符指针——比较字符串 // 字符指针比较字符串内容直接使用关系运算符(==、>、<、>=、<=)即可 cout << (str5 == str6) << endl;//结果是true,输出1 cout << (str5 > str6) << endl;//结果是false,输出0 return 0; }

程序运行结果:

转载请注明原文地址: https://www.6miu.com/read-3450044.html

最新回复(0)