Jef*_*son 2 c++ code-reuse function
可能重复:
C++中不区分大小写的字符串比较
我已经为c ++编写了一些代码来比较两个字符串的相等性.我想要的是校对.我计划将来使用它来制作更多的程序,所以这个功能很好地完成它的工作很重要.这个功能看起来像可重复使用,便携式等吗?是否有更"最新"的方法来做到这一点?我用过ac库,但这是一个c ++程序,是禁忌吗?
谢谢,JH.
//function to compare two strings regardless of case
//-- returns true if the two strings are equal
//-- returns false if
// --the strings are unequal
// --one of the strings is longer than 255 chars
bool isEqual(string str1, string str2){
if(str1.length()!=str2.length()) //the strings are different lengths,
return false; //they can't be equal
if((str1.length()>255) || (str2.length()>255))
return false;
char * cstr1 = new char [str1.length()+1];
strcpy (cstr1, str1.c_str());
char * cstr2 = new char [str2.length()+1];
strcpy (cstr2, str2.c_str());
for(int i=0; i<str1.length()+1; i++){
if(toupper(cstr1[i]) != toupper(cstr2[i]))
return false;
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
ano*_*ous 19
您应该将函数重命名为isEqual_CaseInsensitive,或者将某个名称与函数的名称相匹配.您应该通过引用传递字符串以避免复制您不需要创建字符串的副本来比较它们
bool isEqual_CaseInsensitive(const string& a, const string& b)
{
return a.size() == b.size() &&
std::equal(a.begin(), a.end(), b.begin(), [](char cA, char cB) {
return toupper(cA) == toupper(cB);
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4124 次 |
| 最近记录: |