Write your own strcmp

Write your own strcmp

Write a modified strcmp function which returns -1 if s1 < s2, 0 if s1 = s2, else returns 1. For example, your strcmp should consider “firmcodes.com” and “FIRMCODES.COM” as same string.

Following solution assumes that characters are represented using ASCII representation, i.e., codes for ‘a’, ‘b’, ‘c’, … ‘z’ are 97, 98, 99, … 122 respectively. And codes for ‘A’, “B”, ‘C’, … ‘Z’ are 65, 66, … 95 respectively.

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.

 

 

Suggested Reading

  1. Write a C program to reverse the words in a sentence in place
  2. Write your own trim() or squeeze() function to remove the spaces from a string
  3. Write a C program which does wildcard pattern matching algorithm