c++ - 如何比较两个C字符串指针?

标签 c++

我正在尝试编写代码来检查两个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++的两件事让我很烦:

  • 没有关于pi的标准定义(但我们有一个非常复杂的随机数库,其中一些需要定义pi的值才能实现。)
  • 没有区分大小写的比较两个字符串的标准方法。一般情况比较问题的子集由isupperislowertouppertolower定义。是的,确实,一个完全不区分语言环境的区分大小写的比较超出了C++标准库的范围,但是可以用更简单的术语来设想一个比较。

  • 在Windows中,您使用::_stricmp#include <string.h>
    在Unix中,您使用strcasecmp#include <strcasecmp>
    一个有用的示例,即使它不支持德国的SS,挪威的斜线o,&c。 &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;
    

    关于c++ - 如何比较两个C字符串指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62198140/

    相关文章:

    c++ - 根据条件枚举一组排列

    C++ Visual Studio Express 2010 无法启动程序报错

    c++ - 这个函数调用会被g++优化吗?

    c++ - 在 C++ 中循环字符时出现意外结果

    c++ - 行排序数据到列排序数据的最快转换

    c++ - 引用 std::whatever 或 not_yet_in_std::whatever 的惯用方式是什么?

    c++ - 为什么我不会在C++中为此结构使用构造函数?

    c++ - 在 Linux 中使用 gps timestamp_t 结构设置系统时间

    c++ - 为什么将 const 对象传递给需要非常量模板类型参数的模板化函数会导致编译错误?

    c++ - perf 启用调用图的解构