在 C++ 中,我们需要对 string 字符串进行对比,我们除了可以使用 == 号或者使用 !=,还可以使用字符串的 compare 函数。
int n = s1.compare(s2);
n = s1.compare(1, 2, s2, 0, 3); //比较s1的子串 (1,2) 和s2的子串 (0,3)
n = s1.compare(0, 2, s2); // 比较s1的子串 (0,2) 和 s2
n = s1.compare("Hello");
n = s1.compare(1, 2, "Hello"); //比较 s1 的子串(1,2)和"Hello”
n = s1.compare(1, 2, "Hello", 1, 2); //比较 s1 的子串(1,2)和 "Hello" 的子串(1,2)
如果返回值小于 0 表示当前的字符串小;等于 0 表示两个字符串相等;大于 0 表示另一个字符串小。
可以使用字符串的 compare 函数,来对比字符串 s1 和字符串 s2 是否相等。
使用字符串的 compare 函数,实现字符串的相等对比
#include <iostream>
using namespace std;
int main()
{
cout << "嗨客网(www.haicoder.net)\n" << endl;
string s1 = "Hello";
string s2 = "HaiCoder";
int res1 = s1.compare(s2);
int res2 = s1.compare(1, 2, s2, 0, 3);
int res3 = s1.compare(0, 2, s2);
int res4 = s1.compare("Hello");
int res5 = s1.compare(1, 2, "He");
int res6 = s1.compare(1, 2, "Hello", 1, 2);
cout << "res1 = " << res1 << ", res2 = " << res2 << ", res3 = " << res3 << endl;
cout << "res4 = " << res4 << ", res5 = " << res5 << ", res6 = " << res6 << endl;
}
程序运行后,控制台输出如下:
我们使用 compare,实现了字符串 string 的相等对比。
在 C++ 中,我们需要对 string 字符串进行对比,我们除了可以使用 == 号或者使用 !=,还可以使用字符串的 compare 函数。