Напишите свой собственный strcmp, который игнорирует регистры

Опубликовано: 21 Января, 2022

Напишите модифицированную функцию strcmp, которая игнорирует регистры и возвращает -1, если s1 <s2, 0, если s1 = s2, иначе возвращает 1. Например, ваш strcmp должен рассматривать «GeeksforGeeks» и «geeksforgeeks» как одну и ту же строку.

Источник: набор интервью Microsoft 5.

Следующее решение предполагает, что символы представлены с использованием представления ASCII, т. Е. Коды для «a», «b», «c»,… «z» равны 97, 98, 99,… 122 соответственно. И коды для «A», «B», «C»,… «Z» - 65, 66,… 95 соответственно.

Following are the detailed steps.
1) Iterate through every character of both strings and do following for each character.
a) If str1[i] is same as str2[i], then continue.
b) If inverting the 6th least significant bit of str1[i] makes it same as str2[i], then continue. For example, if str1[i] is 65, then inverting the 6th bit will make it 97. And if str1[i] is 97, then inverting the 6th bit will make it 65.
c) If any of the above two conditions is not true, then break.
2) Compare the last (or first mismatching in case of not same) characters.

C++

#include <bits/stdc++.h>
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: "<<ic_strcmp("Geeks", "apple") <<endl; 
    cout<<"ret: "<<ic_strcmp("", "ABCD")<<endl; 
    cout<<"ret: "<<ic_strcmp("ABCD", "z")<<endl; 
    cout<<"ret: "<<ic_strcmp("ABCD", "abcdEghe")<<endl; 
    cout<<"ret: "<<ic_strcmp("GeeksForGeeks", "gEEksFORGeEKs")<<endl; 
    cout<<"ret: "<<ic_strcmp("GeeksForGeeks", "geeksForGeeks")<<endl; 
    return 0; 
  
//This code is contributed by rathbhupendra

C

#include <stdio.h>
  
/* 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 ", ic_strcmp("Geeks", "apple"));
    printf("ret: %d ", ic_strcmp("", "ABCD"));
    printf("ret: %d ", ic_strcmp("ABCD", "z"));
    printf("ret: %d ", ic_strcmp("ABCD", "abcdEghe"));
    printf("ret: %d ", ic_strcmp("GeeksForGeeks", "gEEksFORGeEKs"));
    printf("ret: %d ", ic_strcmp("GeeksForGeeks", "geeksForGeeks"));
    return 0;
}

Выход:

ret: 1
ret: -1
ret: -1
ret: -1
ret: 0
ret: 0

Эта статья составлена Нарендрой Кангралкар . Пожалуйста, напишите комментарии, если вы обнаружите что-то неправильное, или вы хотите поделиться дополнительной информацией по теме, обсужденной выше.

Вниманию читателя! Не прекращайте учиться сейчас. Освойте все важные концепции DSA с помощью самостоятельного курса DSA по приемлемой для студентов цене и будьте готовы к работе в отрасли. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .

Если вы хотите посещать живые занятия с отраслевыми экспертами, пожалуйста, обращайтесь к Geeks Classes Live и Geeks Classes Live USA.

РЕКОМЕНДУЕМЫЕ СТАТЬИ