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) {
//convert s1 and s2 into lower case strings
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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP