我正在尝试编写代码来检查两个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++的两件事让我很烦:
isupper
,islower
,toupper
和tolower
定义。是的,确实,一个完全不区分语言环境的区分大小写的比较超出了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/