C ++中不区分大小写的字符串比较
在C++中,标准库中有字符串。在此程序中,我们将看到如何检查两个字符串是否相同。在这种情况下,我们将忽略该情况。
这里的逻辑很简单。我们将整个字符串转换为小写或大写字符串,然后进行比较并返回结果。
我们使用算法库来获取转换函数,以将字符串转换为小写字符串。
Input: Two strings “Hello WORLD” and “heLLO worLD” Output: Strings are same
算法
Step 1: Take two strings str1, and str2 Step 2: Convert str1, and str2 into lowercase form Step 3: Compare str1 and str2 Step 4: End
范例程式码
#include<iostream>
#include <algorithm>
using namespace std;
int case_insensitive_match(string s1, string s2) {
//将s1和s2转换为小写字符串
transform(s1.begin(), s1.end(), s1.begin(), ::tolower);
transform(s2.begin(), s2.end(), s2.begin(), ::tolower);
if(s1.compare(s2) == 0)
return 1; //The strings are same
return 0; //not matched
}
main() {
string s1, s2;
s1 = "Hello WORLD";
s2 = "heLLO worLD";
if(case_insensitive_match(s1, s2)) {
cout << "Strings are same";
}else{
cout << "Strings are not same";
}
}输出结果
Strings are same