C - Function strcmpi() to Compare Strings Ignoring Case.


IncludeHelp 18 August 2016

In this code snippet we will learn how we can compare strings ignoring lower and upper case in c programming language?

strcmpi() is a library function of string.h header file, this function does not check strings cases, if strings are same (in any case Upper/Lower) it will return 0 otherwise it will return the difference of first dissimilar characters (i.e. non zero value).

For Example - we have two strings "Hello World!" and "HELLO WORLD!", strcmp() function will return 0 becuase strings are same.

Note: This function will not work in GCC Linux, for that we provided a program below this program in which we impleted strcmpi() function.

C Code Snippet - Compare Strings using strcmpi(), Ignoring Upper, Lower Cases

/*C - Function strcmpi() to Compare Strings Ignoring Case.*/

#include <stdio.h>
#include <string.h>

int main(){
	
	char str1[30];
	char str2[30];
	
	printf("Enter string1: ");
	fgets(str1,30,stdin);
	
	printf("Enter string2: ");
	fgets(str2,30,stdin);
	
	if(strcmpi(str1,str2)==0)
		printf("Both strings are same.\n");
	else
		printf("Both strings are not same.\n");
	
	return 0;
}

    Enter string1: Hello World!
    Enter string2: HELLO WORLD!
    Both strings are same.

User Defined Function strcmpi() for GCC, G++ and Other Compliers

/*C - Function strcmpi() to Compare Strings Ignoring Case.*/

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int strcmpi(char* s1, char* s2){
    int i;
    
    if(strlen(s1)!=strlen(s2))
        return -1;
        
    for(i=0;i<strlen(s1);i++){
        if(toupper(s1[i])!=toupper(s2[i]))
            return s1[i]-s2[i];
    }
    return 0;
}

int main(){
	
	char str1[30];
	char str2[30];
	
	printf("Enter string1: ");
	fgets(str1,30,stdin);
	
	printf("Enter string2: ");
	fgets(str2,30,stdin);
	
	if(strcmpi(str1,str2)==0)
		printf("Both strings are same.\n");
	else
		printf("Both strings are not same.\n");
	
	return 0;
}

    Enter string1: Hello World!
    Enter string2: HELLO WORLD!
    Both strings are same.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.