ที่นี่เราจะดูวิธีเปรียบเทียบสองสตริงใน C ++ C ++ มีคลาสสตริง นอกจากนี้ยังมีฟังก์ชัน Compare() ในไลบรารีมาตรฐานเพื่อเปรียบเทียบสตริง แต่ในที่นี้เราจะใช้ตัวดำเนินการตามเงื่อนไข เช่น ==, !=, <,>, <=,>=ตัวดำเนินการเหล่านี้ตรวจสอบอักขระสตริงตามอักขระ ให้เราดูโค้ดเพื่อรับแนวคิดที่ดีขึ้น
ตัวอย่าง
#include<iostream>
using namespace std;
void compareStrings(string s1, string s2) {
if (s1 != s2)
cout << s1 << " is not equal to "<< s2 << endl;
else if(s1 == s2)
cout << "Strings are equal";
if (s1 > s2)
cout << s1 << " is greater than "<< s2 << endl;
else if(s1 < s2)
cout << s2 << " is greater than "<< s1 << endl;
}
int main() {
string s1("hello");
string s2("helLo");
compareStrings(s1, s2);
} ผลลัพธ์
hello is not equal to helLo hello is greater than helLo