Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

การเปรียบเทียบ String Object ด้วย Relational Operators ใน C++

ใน C++ คลาส string รองรับตัวดำเนินการเปรียบเทียบเชิงสัมพันธ์ (Relational Operators): ==, !=, <, >, <=, >=

ตัวดำเนินการเหล่านี้เปรียบเทียบแบบ Lexicographical (ตามลำดับตัวอักษร) โดยเปรียบเทียบตัวอักษรทีละตัว

ตัวอย่างโค้ด

#include <iostream>
using namespace std;

void compareStrings(string s1, string s2) {
    if (s1 != s2)
        cout << s1 << " is not equal to " << s2 << endl;
    else
        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);
    return 0;
}

ผลลัพธ์

hello is not equal to helLo
hello is greater than helLo

ความแตกต่างกับ compare()

  • compare() คืนค่าตัวเลข (0, บวก, ลบ)
  • Relational operators คืนค่า bool (true/false)
  • ทั้งคู่ทำงานแบบ Case-sensitive เหมือนกัน

เมื่อไหร่ควรใช้ไหน?

  • ใช้ ==, !=, < สำหรับเงื่อนไข if/while (อ่านง่ายกว่า)
  • ใช้ compare() เมื่อต้องการทราบ "มากกว่า/น้อยกว่าแค่ไหน" (ค่าตัวเลข)