C++ 的 compare 和 wcsicmp

C++提供了std::string::compare和wcsicmp两个函数进行字符串比较。compare是std::string的成员函数,区分大小写,返回整数表示比较结果。wcsicmp是C库函数,用于宽字符串的比较,大小写不敏感。两者都可用于判断字符串的相对顺序或相等性。

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

C++ 中有两种比较字符串的函数:comparewcsicmp

  1. compare()

compare() 函数是 std::string 类型的成员函数,用于比较两个字符串是否相等,返回一个整数表示两个字符串的比较结果。该函数可以接受一个 std::string 类型参数,或者 C 风格字符串(以空字符结尾的字符数组)参数。

以下是一个示例:

#include <iostream>
#include <string>

int main()
{
    std::string str1 = "hello";
    std::string str2 = "world";

    int result = str1.compare(str2);

    if (result < 0)
    {
        std::cout << "str1 is less than str2" << std::endl;
    }
    else if (result > 0)
    {
        std::cout << "str1 is greater than str2" << std::endl;
    }
    else
    {
        std::cout << "str1 is equal to str2" << std::endl;
    }

    return 0;
}

在上面的示例中,compare() 函数比较了两个字符串 str1str2。它返回一个整数值,表示两个字符串的比较结果。如果返回值是负数,那么第一个字符串小于第二个字符串;如果返回值是正数,那么第一个字符串大于第二个字符串;如果返回值是零,那么两个字符串相等。

  1. wcsicmp()

wcsicmp() 函数是一个 C 标准库函数,用于比较两个 C 风格的宽字符串是否相等,大小写不敏感。在 C++ 中,它可以使用头文件 cwchar 中的 wcsicmp() 函数调用。

以下是一个示例:

#include <iostream>
#include <cwchar>

int main()
{
    const wchar_t* str1 = L"HELLO";
    const wchar_t* str2 = L"hello";

    int result = std::wcsicmp(str1, str2);

    if (result < 0)
    {
        std::wcout << L"str1 is less than str2" << std::endl;
    }
    else if (result > 0)
    {
        std::wcout << L"str1 is greater than str2" << std::endl;
    }
    else
    {
        std::wcout << L"str1 is equal to str2" << std::endl;
    }

    return 0;
}

在上面的示例中,wcsicmp() 函数比较了两个宽字符串 str1str2。它返回一个整数值,表示两个字符串的比较结果。如果返回值是负数,那么第一个字符串小于第二个字符串;如果返回值是正数,那么第一个字符串大于第二个字符串;如果返回值是零,那么两个字符串相等。需要注意的是,函数 wcsicmp() 在比较字符串时忽略字母的大小写。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值