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

2022-08-01 14:29:14

字符串比较

在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;
}

char指针与char数组的区别

char *p = “helloworld”;
char p[20] = “helloworld”;

第一个情况下 p 指向的是一个常量区(并以‘\0’作为串的结束), 是不能改变的, 即不能够对p[i]赋值;而第二种情况下, p是一个字符数组, 其是可以改变的,可以对p[i]赋值的。

字符串内存模型

第13篇 C/C++的字符串的内存模型

  • 作者:低头看天,抬头走路
  • 原文链接:https://blog.csdn.net/rusbme/article/details/98473899
    更新时间:2022-08-01 14:29:14