ใน 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