Comparing fixed number of characters of two strings in C language

By: IncludeHelp, on 23 JAN 2017

As we know that strcmp() is used to compare two strings, but the strcmp() compares all the characters (till NULL) of two strings. Whenever we want to compare few characters from a fixed index of two strings, then we cannot use strcmp().

memcmp() - Memory Compare

memcmp() can be used with such case, as this function compares only given number of characters in two strings.

Let's understand with an example, there is a string containing three characters of the department code and the name of the Manager (After one colon and space, check the declaration below in the program). We have to print the Manager's name along with the department name if department code matches with the given (user defined/input department code).

Consider the given statements (code) to compare fixed number of characters (bytes)

char deptDetails[]="HRD: Mr. ABC";
if(memcmp(deptDetails,DEPT_TO_CHECK,3)==0)
{
	printf("Dept. name: Human Resource Department, Manager: %s\n",deptDetails+5);
}

Explanation

Statement memcmp(deptDetails,DEPT_TO_CHECK,3) will compare "HRD" (which is the defined string in macro DEPT_TO_CHECK) with the deptDetails, first three characters will be compared if the characters are equal memcpy() will return 0. If condition matches, program will print the Manager's name from index 5 of string deptDetails.

What is deptDetails+5?

This is the address of 5th index of deptDetails and this will print the complete string from index 5. In this example the string from 5th Index is "Mr. ABC" which is the name of Manager.

Here is the complete program

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

#define DEPT_TO_CHECK "HRD"

int main()
{
	char deptDetails[]="HRD: Mr. ABC";
	if(memcmp(deptDetails,DEPT_TO_CHECK,3)==0)
	{
		printf("Dept. name: Human Resource Department, Manager: %s\n",deptDetails+5);
	}
	else{
		printf("Details not found!!!\n");
	}
	
	return 0;
}

Output

    Dept. name: Human Resource Department, Manager: Mr. ABC



Comments and Discussions!

Load comments ↻





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