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

การเปรียบเทียบสตริงใน C++ ด้วยฟังก์ชัน compare()

ใน C++ คลาส string มีฟังก์ชัน compare() สำหรับเปรียบเทียบสตริง ฟังก์ชันนี้ตรวจสอบตัวอักษรทีละตัว หากพบความแตกต่างจะคืนค่าที่ไม่ใช่ 0

  • คืนค่า 0: สตริงทั้งสองเท่ากัน
  • คืนค่า > 0: สตริงแรกมากกว่าสตริงที่สอง (ตามลำดับเล็กโซอกราฟิก)
  • คืนค่า < 0: สตริงแรกน้อยกว่าสตริงที่สอง

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

#include <iostream>
using namespace std;

void compareStrings(string s1, string s2) {
    int cmp = s1.compare(s2);

    if (cmp != 0)
        cout << s1 << " is not equal to " << s2 << endl;
    else
        cout << "Strings are equal";

    if (cmp > 0)
        cout << s1 << " is greater than " << s2 << " difference is: " << cmp << endl;
    else if (cmp < 0)
        cout << s2 << " is greater than " << s1 << " difference is: " << cmp << endl;
}

int main() {
    string s1("hello");
    string s2("helLo"); // ตัว L ใหญ่ vs เล็ก
    compareStrings(s1, s2);
    return 0;
}

ผลลัพธ์

hello is not equal to helLo
hello is greater than helLo difference is: 1

หมายเหตุ

การเปรียบเทียบเป็น Case-sensitive เนื่องจากค่า ASCII ของ 'L' (76) น้อยกว่า 'l' (108) ทำให้ "hello" มากกว่า "helLo"