C++-এ দুটি স্ট্রিং তুলনা করার জন্য compare() ফাংশন এবং == অপারেটর ব্যবহার করা যায়। প্রশ্ন হলো কেন দুটি আলাদা পদ্ধতি আছে? কি কোনো পার্থক্য আছে?
compare() এবং == অপারেটরের মধ্যে কিছু বেসিক পার্থক্য রয়েছে। C++-এ == অপারেটর স্ট্রিংয়ের জন্য ওভারলোডেড থাকে যাতে দুটি স্ট্রিং একই কিনা চেক করা যায়। একই হলে এটি ১ রিটার্ন করে, নয়লে ০। এটি বুলিয়ান টাইপ ফাংশনের মতো।
compare() ফাংশন দুটি ভিন্ন জিনিস রিটার্ন করে। যদি দুটি সমান হয়, তবে এটি ০ রিটার্ন করে। যদি ক্যারেক্টার s এবং t-এ মিসম্যাচ পাওয়া যায়, এবং s, t-এর চেয়ে ছোট হয়, তবে এটি -১ রিটার্ন করে, অন্যথায় +১। এটি ASCII কোড ব্যবহার করে মিল চেক করে।
উদাহরণ কোড
#include <iostream>
using namespace std;
int main() {
string str1 = "Hello";
string str2 = "Help";
string str3 = "Hello";
cout << "Comparing str1 and str2 using ==, Res: " << (str1 == str2) << endl; // 0 for no match
cout << "Comparing str1 and str3 using ==, Res: " << (str1 == str3) << endl; // 1 for match
cout << "Comparing str1 and str2 using compare(), Res: " << str1.compare(str2) << endl; // -1
cout << "Comparing str1 and str3 using compare(), Res: " << str1.compare(str3) << endl; // 0
}আউটপুট
Comparing str1 and str2 using ==, Res: 0 Comparing str1 and str3 using ==, Res: 1 Comparing str1 and str2 using compare(), Res: -1 Comparing str1 and str3 using compare(), Res: 0