c++ string compare 简单实验

本文通过四个实验详细探讨了C++中使用std::string的compare方法进行字符串比较的过程及返回值的意义,包括基本的相等性检查、不同情况下返回值的特点、大小写敏感性的影响以及字符差异对比较结果的具体影响。

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

代码 

// ConsoleApplication24.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include<string>
using namespace std;

void test1() {
    cout << "----基本实验-----\n";
    string str1 = "a";
    string str2 = "b";
    if (0 == str1.compare(str2)) {
        cout << "相等" << "\n";
    }
    else {
        cout << "不相等" << "\n";
    }
}
//相等和不相等的返回值是什么
void test2() {
    cout <<"\n----相等和不相等的返回值是什么-----\n";
    string str1 = "ab1";
    string str2 = "ab1";
    string str3 = "abc";
    int n = str1.compare(str2);
    cout <<"相等"<<n<< "\n";
    n = str1.compare(str3);
    cout << "不等" << n << "\n";
}
// 大小字符对返回值的影响
void test3() {
    cout << "\n----大小字符对返回值的影响-----\n";
    string str1 = "123";
    string str2 = "456";
    int n = str1.compare(str2);
    cout << "123.compare(456)" << n << "\n";
    n = str2.compare(str1);
    cout << "456.compare(123)" << n << "\n";
}
// 判断不同位置的不同是否对值有影响
// 确认没有影响,都是1和-1,没有更大的数
void test4() {
    cout << "\n----判断不同位置的不同是否对值有影响-----\n";
    cout << "----确认没有影响,都是1和-1,没有更大的数-----\n";
    string str1 = "123";
    string str2 = "125";
    int n = str1.compare(str2);
    cout << "123.compare(125)" << n << "\n";
    n = str2.compare(str1);
    cout << "125.compare(123)" << n << "\n";
}
int main()
{
    test1();
    test2();
    test3();
    test4();
    std::cout << "Hello World!\n";
    getchar();
}

运行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值