ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

Home » C programs » C string programs

C program to compare two strings using pointers

Learn: How to compare two strings using pointers in C programming language?

Here, you will learn how to read and compare two strings using pointers in C programming language? In this program, we are taking two strings with maximum number of characters (100) MAX using pointers and comparing the strings character by characters.

Program to compare two strings using pointers in C



#include <stdio.h>

//Macro for maximum number of characters in a string
#define MAX 100

int main()
{
	//declare string variables
	char str1[MAX]={0};
	char str2[MAX]={0};
	
	int loop;	//loop counter
	int flag=1;
	
	//declare & initialize pointer variables
	char *pStr1=str1;
	char *pStr2=str2;
	
	//read strings 
	printf("Enter string 1: ");	
	scanf("%[^\n]s",pStr1);
	printf("Enter string 2: ");	
	getchar(); //read & ignore extra character
	scanf("%[^\n]s",pStr2);	
	
	//print strings
	printf("string1: %s\nstring2: %s\n",pStr1,pStr2);
	
	//comparing strings
	for(loop=0; (*(pStr1+loop))!='\0'; loop++)
	{
		if(*(pStr1+loop) != *(pStr2+loop))
		{
			flag=0;
			break;
		}
	}
	
	if(flag)
		printf("Strings are same.\n");
	else
		printf("Strings are not same.\n");
	
	return 0;	
}

Output

First run:
Enter string 1: IncludeHelp.com 
Enter string 2: Include.com 
string1: IncludeHelp.com
string2: Include.com
Strings are not same.

Second run:
Enter string 1: includehelp.com 
Enter string 2: includehelp.com 
string1: includehelp.com
string2: includehelp.com
Strings are same.

Here, flag is a variable that is assigned by 1 initially, within the loop if any character of first string is not equal to character of second string, and then value of flag will be 0 (loop will be terminated). At the end, we will check if flag is 1, strings are same else strings are not same.

ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.