C++ 中有两种比较字符串的函数:compare
和 wcsicmp
。
- 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()
函数比较了两个字符串 str1
和 str2
。它返回一个整数值,表示两个字符串的比较结果。如果返回值是负数,那么第一个字符串小于第二个字符串;如果返回值是正数,那么第一个字符串大于第二个字符串;如果返回值是零,那么两个字符串相等。
- 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()
函数比较了两个宽字符串 str1
和 str2
。它返回一个整数值,表示两个字符串的比较结果。如果返回值是负数,那么第一个字符串小于第二个字符串;如果返回值是正数,那么第一个字符串大于第二个字符串;如果返回值是零,那么两个字符串相等。需要注意的是,函数 wcsicmp()
在比较字符串时忽略字母的大小写。