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

更新於: 2019 年 7 月 30 日

8K+ 瀏覽量

啟動你的 職業

完成課程並獲得認證

開始
廣告
© . All rights reserved.