mav*_*rik 2 c++ string boost stl
我的问题与此类似,但我有两个字符串(as char *
),任务是strnicmp
用类似的东西替换函数(仅适用于MS VC)boost::iequals
.
注意strnicmp
不是stricmp
- 它只比较前n个字符.
有没有比这更简单的解决方案:
void foo(const char *s1, const char *s2)
{
...
std::string str1 = s1;
std::string str2 = s2;
int n = 7;
if (boost::iequals(str1.substr(0, n), str2)) {
...
}
}
Run Code Online (Sandbox Code Playgroud)
如果确实有必要,请编写自己的函数:
bool mystrnicmp(char const* s1, char const* s2, int n){
for(int i=0; i < n; ++i){
unsigned char c1 = static_cast<unsigned char>(s1[i]);
unsigned char c2 = static_cast<unsigned char>(s2[i]);
if(tolower(c1) != tolower(c2))
return false;
if(c1 == '\0' || c2 == '\0')
break;
}
return true;
}
Run Code Online (Sandbox Code Playgroud)