C++ এ আমরা compare() ফাংশন এবং ==অপারেটর ব্যবহার করে দুটি স্ট্রিং তুলনা করতে পারি। তাহলে প্রশ্ন হল দুটি ভিন্ন পদ্ধতি কেন? কোন পার্থক্য আছে কি না?
তুলনা() এবং ==অপারেটরের মধ্যে কিছু মৌলিক পার্থক্য রয়েছে। C++-এ ==অপারেটরটি স্ট্রিং-এর জন্য ওভারলোড করা হয় যাতে উভয় স্ট্রিং একই কিনা তা পরীক্ষা করা যায়। যদি তারা একই হয় তবে এটি 1 ফেরত দেবে, অন্যথায় 0। সুতরাং এটি বুলিয়ান টাইপ ফাংশনের মতো।
compare() ফাংশন দুটি ভিন্ন জিনিস প্রদান করে। উভয়ই সমান হলে, এটি 0 প্রদান করবে, যদি অক্ষর s এবং t এর জন্য অমিল পাওয়া যায়, এবং যখন s টি থেকে কম হয়, তখন এটি -1 প্রদান করে, অন্যথায় যখন s টি থেকে বড় হয় তখন এটি +1 প্রদান করে। এটি 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 no match cout << "Comparing str1 and str2 using compare(), Res: " << str1.compare(str2) << endl;//checking smaller and greater cout << "Comparing str1 and str3 using compare(), Res: " << str1.compare(str3) << endl;//0 for no match }
আউটপুট
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