- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Write your own strcmp that ignores cases in C++
Here, we have to create a strcmp (string compare) function that compares two string but ignores cases of the characters of the string. The function will return -1 if string1 < string2, 0 if string1 = string2, 1 if string1 > string2.
Let’s take an example to understand the problem,
Input
string1 = “Hello” , string2 = “hello”
Output
0
To create our own strcmp function that ignores cases while comparing the strings. We will iterate through all characters of both the strings, if characters at ith index are the same i.e. string1[i] == string2[i], continue. If string1[i] > string2[i], return 1. If string1[i] < string2[i], return -1. If the string ends returns 0.
Here, we have to ignore cases, so A and a will be considered the same. We will use the ASCII values of the characters, then ASCII for a = 97 will be equal to ASCII of A = 65.
Program to show the implementation of our solution,
Example
#include <iostream> using namespace std; int strcmpFunc(string string1, string string2){ int i; for (i = 0; string1[i] && string2[i]; ++i){ if (string1[i] == string2[i] || (string1[i] ^ 32) == string2[i]) continue; else break; } if (string1[i] == string2[i]) return 0; if ((string1[i] | 32) < (string2[i] | 32)) return -1; return 1; } int main(){ cout<<"Compareing string using our strcmp function :\n"; cout<<"Result: "<<strcmpFunc("HELLO", "hello")<<endl; cout<<"Result: "<<strcmpFunc("", "Hello")<<endl; cout<<"Result: "<<strcmpFunc("Tutorials", "Pint")<<endl; cout<<"Result: "<<strcmpFunc("afdadsa", "rewf")<<endl; cout<<"Result: "<<strcmpFunc("tutorialspoint", "TUTORIALSpoint")<<endl; return 0; }
Output
Compareing string using our strcmp function − Result: 0 Result: -1 Result: 1 Result: -1 Result: 0
- Related Articles
- Write your own memcpy() in C
- Write your own atoi() in C++
- Write your own memcpy() and memmove() in C++
- How to write your own header file in C?\n
- How to write your own LaTeX preamble in Matplotlib?
- Implement your own itoa() in C
- strcmp() in C/C++
- How will implement Your Own sizeof in C
- Implement your own sizeof operator using C++
- Print with your own font using C#
- Build Your Own Botnet
- How to write my own header file in C?
- When should we write our own assignment operator in C++?
- Difference between strncmp() and strcmp() in C/C++
- Can you build your own sundial?
