字符串的比较

本文探讨了C++中字符串的比较方法,包括使用比较运算符(>、<、==等)和String类的compare()函数。重点介绍了compare()函数的不同重载形式及其返回值含义,强调了在进行字符串比较时需避免NULL值导致的异常。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1)我们比较常用的是比较运算符

String 类的常见运算符包括 >、<、==、>=、<=、!=。
示例代码:

#include <iostream>
#include <string>
using namespace std;
int main ()
{
    string str1 = "DEF";
    string str2 = "ABC";
    if(str1<str2) 
    	cout<<"str2 is bigger";
    else if(str1>str2)
        cout<<"str1 is bigger";
    else
        cout<<"they are the same";
      return 0;
}

读者应注意,对于参加比较的两个字符串,任一个字符串均不能为 NULL,否则程序会异常退出。

2)Basic_string 类模板提供了 compare() 函数,支持多参数处理。该函数返回一个整数来表示比较结果。如果相比较的两个子串相同,compare() 函数返回 0,否则返回非零值。
compare() 的原型如下:
int compare (const basic_string& s) const;
int compare (const Ch* p) const;
int compare (size_type pos, size_type n, const basic_string& s) const;
int compare (size_type pos, size_type n, const basic_string& s,size_type pos2, size_type n2) const;
int compare (size_type pos, size_type n, const Ch* p, size_type = npos) const;

示例代码:

#include <iostream>
#include <string>
using namespace std;
int main ()
{
    string A ("aBcdef");
    string B ("AbcdEf");
    int m=A.compare (B); //完整的A和B的比较
    int n=A.compare(1,5,B,4,2); //"Bcdef"和"Ef"比较
    cout << "m = " << m <<", n = " << n << endl;
    cin.get();
    return 0;
}

执行结果为:    m = 1,  n = -1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值