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

字符串比较

在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++的字符串的内存模型

  • 4
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值