Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

So sánh đối tượng String bằng toán tử quan hệ trong C++

C++ cho phép so sánh chuỗi trực tiếp bằng các toán tử ==, !=, <, >, <=, >=. Các toán tử này so sánh theo thứ tự từ điển (lexicographical) ký tự bởi ký tự.

Ví dụ

#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);
}

Kết quả

hello is not equal to helLo
hello is greater than helLo