簡體   English   中英

如何比較兩個 C 字符串指針?

[英]How do I compare two C-string pointers?

我正在嘗試編寫代碼來檢查兩個 C 字符串變量是否相同,除非大小寫不同。 給定兩本輸入books BOOKS ,程序應該返回 1,而Incorrect correct應該返回 0。我的代碼沒有准確地打印出來。

#include <iostream>
#include <cctype>
#include <cstring>
using namespace std;
int Judge_Char(const char* str1,const char* str2){
    char first[20],second[20];
    for(int i=0;i<20;i++){
        first[i]=str1[i];
        second[i]=str2[i]; //assigned pointers to variable
    }                      //bc I didn't know other ways to compare

    int k=0,l=0;
    for(k=0;first[k]!='\0';k++);
    for(l=0;second[l]!='\0';l++); //got the length of the chars here


    for(int i=0;i<k;i++){
        first[i]=toupper(first[i]);
    }                             //i converted them to same case here
    for(int i=0;i<l;i++){
        second[i]=toupper(second[i]);
    }

    for(int n=0;n<k;n++){
        for(int m=0;m<l;m++){
            if(first[n]==second[m]){
                return 1;           // i check whether they are same or not
            }
            else{
                return 0;
            }
        }
    }
}


int main()
{
    char a[20],b[20];
    cin>>a>>b;
    int flag=Judge_Char(a,b);
    cout<<flag<<endl;
    return 0;
}

關於 C++ 有兩件事讓我很惱火:

  1. pi沒有標准定義(但我們有一個非常復雜的隨機數庫,其中一些需要定義pi的值才能實現)。

  2. 在不區分大小寫的基礎上比較兩個字符串沒有標准方法。 一般情況比較問題的一個子集由isupperislowertouppertolower定義。 是的,確實,一個完整的區域感知不區分大小寫比較超出了 C++ 標准庫的 scope,但可以用更簡單的術語來設想。

在 Windows 你使用::_stricmp#include <string.h>

在 Unix 中,您使用strcasecmp#include <strcasecmp>


一個有用的例子,即使它不支持德國 SS、挪威斜線 o 等。 &C。

struct iLT
{
    bool operator()(const std::string& lhs, const std::string& rhs) const {
        return strcasecmp(lhs.c_str(), rhs.c_str()) < 0;
    }
};

typedef std::map<std::string, double, iLT> MapWithCaseInsensitiveKeys;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM