編寫一個可以在 C++ 中忽略大小寫的 strcmp


我們需要編寫的 strcmp(字串比較)函式在比較兩個字串時應忽略大小寫。若字串1 < 字串2,函式返回 -1;若字串1 = 字串2,函式返回 0;若字串1 > 字串2,函式返回 1。

讓我們舉個例子來理解這個問題:

輸入

string1 = “Hello” , string2 = “hello”

輸出

0

要編寫我們的 strcmp 函式,需要在比較字串時忽略大小寫。我們要遍歷兩個字串中的所有字元,如果這兩個字串中第 i 個索引處的字元相同,即 string1[i] == string2[i],則繼續。如果 string1[i] > string2[i],則返回 1。如果 string1[i] < string2[i],則返回 -1。如果字串結束了,則返回 0。

這裡,我們需要忽略大小寫,所以 A 和 a 將被視為相同。我們將使用字元的 ASCII 值,比如 a 的 ASCII 值 97 等於 A 的 ASCII 值 65。

程式來展示我們解決方案的實現:

示例

線上演示

#include <iostream>
using namespace std;
int strcmpFunc(string string1, string string2){
   int i;
   for (i = 0; string1[i] && string2[i]; ++i){
      if (string1[i] == string2[i] || (string1[i] ^ 32) == string2[i])
         continue;
      else
      break;
   }
   if (string1[i] == string2[i])
      return 0;
   if ((string1[i] | 32) < (string2[i] | 32))
      return -1;
   return 1;
}
int main(){
   cout<<"Compareing string using our strcmp function :\n";
   cout<<"Result: "<<strcmpFunc("HELLO", "hello")<<endl;
   cout<<"Result: "<<strcmpFunc("", "Hello")<<endl;
   cout<<"Result: "<<strcmpFunc("Tutorials", "Pint")<<endl;
   cout<<"Result: "<<strcmpFunc("afdadsa", "rewf")<<endl;
   cout<<"Result: "<<strcmpFunc("tutorialspoint", "TUTORIALSpoint")<<endl;
   return 0;
}

輸出

Compareing string using our strcmp function −
Result: 0
Result: -1
Result: 1
Result: -1
Result: 0

更新時間:2020 年 4 月 17 日

704 次瀏覽

開啟你的職業生涯

透過完成該課程獲得認證

開始
廣告