📅  最后修改于: 2021-05-25 07:11:50             🧑  作者: Mango
编写一个修改后的strcmp函数,该函数将忽略大小写,如果s1
资料来源:Microsoft Interview Set 5
以下解决方案假设字符使用ASCII表示,即表示为’A’, ‘B’, ‘C’的代码,… ‘Z’是97,98,99,…分别122。 “ A”,“ B”,“ C”,……“ Z”的代码分别为65、66,……95。
以下是详细步骤。
1)遍历两个字符串的每个字符,并对每个字符进行跟随。
… a)如果str1 [i]与str2 [i]相同,则继续。
… b)如果将str1 [i]的第六个最低有效位取反,使其与str2 [i]相同,则继续。例如,如果str1 [i]为65,则将第6位取反将使其变为97。如果str1 [i]为97,则将第6位取反将使其变为65。
… c)如果以上两个条件中的任何一个都不成立,则中断。
2)比较最后一个(或第一个不匹配的字符)。
C++
#include
using namespace std;
/* implementation of strcmp that ignores cases */
int ic_strcmp(string s1, string s2)
{
int i;
for (i = 0; s1[i] && s2[i]; ++i)
{
/* If characters are same or inverting the
6th bit makes them same */
if (s1[i] == s2[i] || (s1[i] ^ 32) == s2[i])
continue;
else
break;
}
/* Compare the last (or first mismatching in
case of not same) characters */
if (s1[i] == s2[i])
return 0;
// Set the 6th bit in both, then compare
if ((s1[i] | 32) < (s2[i] | 32))
return -1;
return 1;
}
// Driver program to test above function
int main()
{
cout<<"ret: "<
C
#include
/* implementation of strcmp that ignores cases */
int ic_strcmp(char *s1, char *s2)
{
int i;
for (i = 0; s1[i] && s2[i]; ++i)
{
/* If characters are same or inverting the
6th bit makes them same */
if (s1[i] == s2[i] || (s1[i] ^ 32) == s2[i])
continue;
else
break;
}
/* Compare the last (or first mismatching in
case of not same) characters */
if (s1[i] == s2[i])
return 0;
// Set the 6th bit in both, then compare
if ((s1[i] | 32) < (s2[i] | 32))
return -1;
return 1;
}
// Driver program to test above function
int main(void)
{
printf("ret: %d\n", ic_strcmp("Geeks", "apple"));
printf("ret: %d\n", ic_strcmp("", "ABCD"));
printf("ret: %d\n", ic_strcmp("ABCD", "z"));
printf("ret: %d\n", ic_strcmp("ABCD", "abcdEghe"));
printf("ret: %d\n", ic_strcmp("GeeksForGeeks", "gEEksFORGeEKs"));
printf("ret: %d\n", ic_strcmp("GeeksForGeeks", "geeksForGeeks"));
return 0;
}
输出:
ret: 1
ret: -1
ret: -1
ret: -1
ret: 0
ret: 0