Q:

C program to compare two strings using pointers

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

Hereflag 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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now