Featured image of post 【C++ 字串處理 #5】C++ strcmp 字串比較 用法整理

【C++ 字串處理 #5】C++ strcmp 字串比較 用法整理

介紹 `std::strcmp()` 用法 — 比較兩個 const char*,傳回 -1(前小)、0(相同)、1(前大)。

前言

當我們要比較兩個字串時,我們可以使用 strcmp

strcmp 用法

當我們有兩個 const char*,我們可以使用 std::strcmp 來比較兩者,
依照第一個字開始比較,如果 apple 跟 book 會先比 a, b,

  • 前小:-1
  • 相同:0
  • 前大:1

範例

void exp_strcmp(){
    const char *a = "apple";
    const char *b = "book";
    cout << strcmp(a, b) << endl;
    cout << strcmp(b, a) << endl;
    cout << strcmp(a, a) << endl;
}
  • 結果:

【C++ 字串處理 #5】C++ strcmp 字串比較 用法整理

Reference

使用 Hugo 建立
主題 StackJimmy 設計