Comparing two strings for exact character wise match or for sort order using strcmp()
A program to compare two strings entered by the user if their all characters are same or which string will come first in the sort order using the function strcmp(str1,str2)
Learning Objectives
- Learning to use strcmp() function.
- Learning comparison for exactly same strings or finding sort order amongst two strings.
Source Code
|
|
Run Output
Code Understanding
char str1[80],str2[80]; //Char array for two strings have been declared here
cout<<“Input string 1: ” ; cin.getline(str1,80);
First string is collected using cin.getline(), so space between words are also allowed.
cout<<endl<<“Input string 2: ” ; cin.getline(str2,80);
Second string is collected here.
int sc=strcmp(str1,str2); //The return value after strcmp(str1,str2) is filled in integer sc.
cout<<“strcmp(str1,str2) returns “<<sc<<endl; //The return value is printed could be typically 0, 1 or -1
if(sc==0) cout<<“Both strings are same”;
When 0 is returned by strcmp then both strings are same for each character match.
else if(sc>0) cout<<“str1 will come after str2 when ascending”;
When a positive value (1) is returned means the ascii value of character in str1 is more than str2 where the mismatch occurs. Comparison after that is not done. This will basically means that when two strings are to be put in ascending order str1 will be kept below str2.
else if(sc<0) cout<<“str2 will come after str1 when ascending”;
When a negative value (-1) is returned means the ascii value of character in str2 is more than str1 where the mismatch occurs. Means that when two strings are to be put in ascending order str2 will be kept below str1.
else ; //This is a dummy instruction which could have been avoided by giving previous instruction without if, but for proper understanding of comparison its has been added.
Notes
- strcmp() may find mismatch of strings even when upper and lower case are different. For example “Taj” and “TaJ” would be different and sort order wise “TaJ” will come before “Taj” as the ascii code of lowercase alphabets are larger than that of its uppercase counterparts.
- On modern compilers the include file cstring can be used instead of string.h for proper Unicode support and other moderns features.
Common Errors
- Students often confuse between finding sort orders when -1 or 1 is returned. Remember first is bigger for postive value and vice-versa.
Suggested Filename(s): strcmp.cpp
Created: 13-Jan-2018 02:00 | Updated: 13-Jan-2018 02:15|
