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?
Problem statement
Given two strings, we have to write a C program to compare them using the pointers.
Comparing two strings using pointers
Below are the steps to compare two strings using the pointers:
- Declare two string variables.
- Create two pointers for strings, and initialize them with the string variables.
- Now, input and print the two strings.
- Now, to compare the strings, use a for loop and compare strings character-wise. If any character (in both strings) is not the same. Then take a flag variable, break the loop, and print the appreciate messages.
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.
In this example, we have used the following C language topics that you should learn:
C String Programs »