C++ String::compare() 函式



C++ 的std::string::compare()函式用於比較兩個字串。它提供了一種按字典順序比較字串物件內容與另一個字串或子字串的方法。它返回一個整數,如下所示:

0:字串相等

<0:呼叫字串小於引數字串。

>0:呼叫字串大於引數字串。

此函式可用於比較整個字串或指定範圍的字元。

語法

以下是 std::string::compare() 函式的語法。

int compare (const string& str) const noexcept;
or
int compare (size_t pos, size_t len, const string& str) const;
int compare (size_t pos, size_t len, const string& str, size_t subpos, size_t sublen) const;
or
int compare (const char* s) const;
int compare (size_t pos, size_t len, const char* s) const;
or
int compare (size_t pos, size_t len, const char* s, size_t n) const;

引數

  • str − 指示另一個字串物件。
  • len − 指示比較字串的長度。
  • pos − 指示對應字串中第一個字元的位置。
  • subpos, sublen − 與上面的 pos 和 len 相同。
  • n − 指示要比較的字元數。
  • s − 指示指向字元陣列的指標。

返回值

它返回一個帶符號整數,指示字串之間的關係。

異常

如果丟擲異常,則字串不會發生任何更改。

示例 1

以下是一個使用 C++ 演示 string::compare 的基本示例。

#include <iostream>
#include <string>
using namespace std;
int main() {
   string X1 = "apple";
   string X2 = "banana";
   int result = X1.compare(X2);
   if (result == 0) {
      cout << " Both are equal " << endl;
   } else if (result < 0) {
      cout << X1 << " is less than " << X2 << endl;
   } else if (result > 0) {
      cout << X1 << " is greater than " << X2 << endl;
   }
   return 0;
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

apple is less than banana

示例 2

在這個例子中,我們比較一個子字串與另一個字串。所以它將輸出結果列印為相等。

#include <iostream>
#include <string>
using namespace std;
int main() {
   string X1 = "Tutorialspoint";
   string X2 = "point";
   int result = X1.compare(9, 5, X2);
   if (result == 0) {
      cout << " Both are equal " << endl;
   } else if (result < 0) {
      cout << X1.substr(6, 5) << " is less than " << X2 << endl;
   } else if (result > 0) {
      cout << X1.substr(6, 5) << " is greater than " << X2 << endl;
   }
   return 0;
}

輸出

如果我們執行上面的程式碼,它將生成以下輸出。

Both string are equal.

示例 3

以下是用 string::compare() 函式比較兩個字串子字串的另一個示例。

#include <iostream>
#include <string>
using namespace std;
int main() {
   string X1 = "hello world";
   string X2 = "goodbye world";
   int result = X1.compare(6, 5, X2, 8, 5);
   if (result == 0) {
      cout << " Both are equal " << endl;
   } else if (result < 0) {
      cout << X1.substr(6, 5) << " is less than " << X2.substr(8, 5) << endl;
   } else {
      cout << X1.substr(6, 5) << " is greater than " << X2.substr(8, 5) << endl;
   }
   return 0;
}

輸出

以下是上述程式碼的輸出。

The substrings are equal.                 

示例 4

在這個例子中,我們將一個字串與空字串進行比較。

#include <iostream>
#include <string>
using namespace std;
int main() {
   string X1 = "hello";
   string X2 = "";
   int result = X1.compare(X2);
   if (result == 0) {
      cout << " Both are equal " << endl;
   } else if (result < 0) {
      cout << X1 << " is lesser than " << X2 << endl;
   } else {
      cout << X1 << " is greater than " << X2 << endl;
   }
   return 0;
}

輸出

以下是上述程式碼的輸出。

hello is greater than  
string.htm
廣告