當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ strcmp()用法及代碼示例

在本教程中,我們將借助示例了解 C++ strcmp() 函數。

C++ 中的 strcmp() 函數比較兩個 null-terminating 字符串 (C-strings)。比較是按字典順序進行的。它在cstring 頭文件中定義。

示例

#include <cstring>
#include <iostream>
using namespace std;

int main() {
  char str1[] = "Megadeth";
  char str2[] = "Metallica";

  // compare str1 and str2 lexicographically
  int result = strcmp(str1, str2);

  cout << result;

  return 0;
}

// Output: -1

strcmp() 語法

用法:

strcmp(const char* lhs, const char* rhs);

這裏,

  • lhs 代表左側
  • rhs 代表右手邊

參數:

strcmp() 函數采用以下參數:

  • lhs- 指向需要比較的C-string的指針
  • rhs- 指向需要比較的C-string的指針

返回:

strcmp() 函數返回:

  • a 正值如果第一個不同的字符lhs大於對應的字符rhs.
  • a 負值如果第一個不同的字符lhs小於對應的字符rhs.
  • 0如果lhsrhs是平等的。

strcmp() 原型

cstring 頭文件中定義的strcmp() 原型為:

int strcmp( const char* lhs, const char* rhs );
  • strcmp() 按字典順序比較lhsrhs 的內容。
  • 結果的符號是在 lhsrhs 中不同的第一對字符之間的差異符號。

strcmp() 未定義行為

的行為strcmp()不明確的如果:

  • lhsrhs 中的任何一個都不指向 C-strings(以空字符結尾的字符串)

示例 1:C++ strcmp()

#include <cstring>
#include <iostream>
using namespace std;

int main() {
  char str1[] = "Megadeth";
  char str2[] = "Metallica";

  // returns -1 because "Megadeth" < "Metallica" lexicographically
  int result = strcmp(str1, str2);

  cout << "Comparing " << str1 << " and " << str2 << ": " << result << endl;

  // returns 1 because  "Metallica" > "Megadeth" lexicographically
  result = strcmp(str2, str1);

  cout << "Comparing " << str2 << " and " << str1 << ": " << result << endl;

  // returns 1 because  "Megadeth" = "Megadeth" lexicographically
  result = strcmp(str1, str1);

  cout << "Comparing " << str1 << " and " << str1 << ": " << result;

  return 0;
}

輸出

Comparing Megadeth and Metallica: -1
Comparing Metallica and Megadeth: 1
Comparing Megadeth and Megadeth: 0

示例 2:在用戶定義的函數中使用 strcmp()

#include <cstring>
#include <iostream>
using namespace std;

// function to display the result of strcmp()
void display(char *lhs, char *rhs) {

  // compare display() parameters lhs and rhs   
  int result = strcmp(lhs, rhs);

  if (result > 0)
    cout << rhs << " precedes " << lhs << endl;
  else if (result < 0)
    cout << rhs << " follows " << lhs << endl;
  else
    cout << lhs << " and " << rhs << " are same" << endl;
}

int main() {
  char str1[] = "Armstrong";
  char str2[] = "Army";

  // lhs = str1, rhs = str2
  display(str1, str2);

  // lhs = str2, rhs = str1
  display(str2, str1);

  // lhs = str1, rhs = str1
  display(str1, str1);

  // lhs = str2, rhs = str2
  display(str2, str2);

  return 0;
}

輸出

Army follows Armstrong
Armstrong precedes Army
Armstrong and Armstrong are same
Army and Army are same

相關用法


注:本文由純淨天空篩選整理自 C++ strcmp()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。