Tutorial Playlist
The C programming language, known for its wide-ranging flexibility and low-level capabilities, offers a plethora of in-built functions, among which, the string handling functions play a crucial role. One such function is the strcmp() in C. This article explores the anatomy of strcmp(), its parameters, syntax, and the return value it provides when used in a program.
In C, a string is an array of characters terminated by a null character ('\0'). While handling strings, comparing two strings is a common operation. For instance, string comparison is vital in sorting, searching operations, or even in login systems where we compare the input password with the stored password. strcmp() function is a handy tool for such situations. This article elucidates this function, its usage, syntax, and strcmp example.
strcmp() stands for "string compare". It is a built-in function in C, included in the string.h library. The primary role of this function is to compare two strings lexicographically. The comparison is based on ASCII values of the characters.
The syntax of the strcmp() function is simple and easy to understand. It's as follows:
int strcmp(const char *str1, const char *str2); |
Here, str1 and str2 are the two strings that need to be compared.
The strcmp() in C takes two parameters:
1. str1 – the first string for comparison.
2. str2 – the second string to be compared with the first string.
Both str1 and str2 are pointers to the first characters of the strings to be compared.
The prototype for the strcmp() function in the C library is:
int strcmp(const char *str1, const char *str2); |
It returns an integer value after comparison, which leads us to the next section, strcmp return value in c.
The strcmp() function returns an integer that can tell you whether the strings are equal and which one would come first in a dictionary. The value returned by strcmp() depends on the ASCII values of the characters in the strings.
Let's elaborate on each case:
Zero: This return value signifies that both strings are equal. This means every corresponding pair of characters in the two strings is the same.
Example:
#include <stdio.h> |
Output: Return value: 0
Positive Value: A positive return value indicates that the first string (str1) is greater than the second string (str2). The positive value is the difference between the ASCII value of the character where the difference was first spotted.
Example:
#include <stdio.h> |
Output: Return value: 25 (Here, 'Z' has the ASCII value 90 and 'A' has 65. Thus, 90-65=25)
Negative Value: A negative return value represents that the first string (str1) is less than the second string (str2). The negative value is the difference between the ASCII value of the character where the difference was first spotted.
Example:
#include <stdio.h> |
Output: Return value: -25 (Here, 'A' has the ASCII value 65 and 'Z' has 90. Thus, 65-90=-25)
Please note that the strcmp() function is case-sensitive. It treats uppercase and lowercase characters as different, as they have different ASCII values. If you want to compare strings in a case-insensitive way, you can use the strcasecmp() function instead.
The strcmp() function in C provides a straightforward way to compare two strings. The steps below outline how to use this function in your code:
Include the Header File: strcmp() is part of the string.h header file. So, the first step is to include this header in your C program. This is done using the #include directive as shown below:
#include <string.h> |
Declare Strings: Next, declare the strings that you want to compare. Strings in C are essentially arrays of characters terminated by a null character ('\0'). Here's an example of how to declare two strings:
char str1[] = "upGrad"; |
Use strcmp(): Now you can use strcmp() to compare the two strings. Pass the strings as arguments to strcmp(). It will compare both strings lexicographically and return an integer based on the comparison.
int result = strcmp(str1, str2);
Process the Result: Based on the return value, you can determine whether the two strings are equal or which one is greater. A common way to handle this is through an if-else statement, as shown:
if(result == 0) { |
Here's a complete example that puts it all together:
#include <stdio.h> |
The strcmp() function in C works by performing a lexicographic comparison, which is similar to how words are arranged in a dictionary. The function begins by comparing the first character from each of the two strings. If these characters are equal, it proceeds to the next pair. This process continues until it encounters a pair of characters that aren't equal or until it reaches the end of one or both strings (a null character '\0').
Let's dive a bit deeper into its working mechanism:
1. Character by Character Comparison: The function starts comparing the first character of each string. If they are equal, it moves to the next characters of the strings. strcmp() compares the ASCII values of each pair of characters from str1 and str2.
2. First Mismatch or Null Character: The comparison process stops when it encounters a pair of characters that aren't equal or a null character '\0' which signifies the end of a string.
3. Determining the Result: If it finds a pair where the character from str1 is not equal to the character from str2, it subtracts the ASCII value of the character in str2 from the ASCII value of the character in str1 and returns this value. If no such pair is found (meaning the strings are equal until the end of one or both strings), it subtracts the length of str2 from the length of str1 and returns this value.
To put it in simpler terms:
Thus, strcmp() helps determine not only whether the two strings are equal but also, if they aren't, which one would come first in lexicographical (dictionary) order.
Using strcmp() in C, you can compare two strings and determine whether they are the same or which one would come first in a dictionary. Let's consider some examples to see this in action.
#include <stdio.h> |
In this program, the strcmp() function compares Inputstr1 and Inputstr2. As both are the same, it returns 0, and the program outputs "Strings are equal."
#include <stdio.h> |
Here, str1 is lexicographically less than str2. strcmp() will return a negative value, and the output will be "str1 is lexicographically less than str2."
#include <stdio.h> |
In this example, str1 is lexicographically greater than str2, so strcmp() will return a positive value. The output will be "str1 is lexicographically greater than str2."
The strcmp() function is an efficient way to compare two strings in c. It provides an easy-to-use interface for comparing strings lexicographically. However, in some cases, you might want to string compare in C without using strcmp(). In those instances, you can make use of loops and conditionals, though it requires a bit more work.
Understanding such intrinsic details of strcmp() in C enriches your programming knowledge and skills. As a part of your learning journey, consider checking out upGgrad's Master of Science in Data Science program, offered under the guidance of Liverpool John Moores University. This course will surely bolster your coding abilities and broaden your horizons in the tech industry.
1. Can strcmp() be used to compare strings of different lengths?
Yes, strcmp() can compare strings of different lengths. It keeps comparing corresponding characters of both the strings until it encounters a null character.
2. How does strcmp() compare strings lexicographically?
strcmp() compares strings character by character using their ASCII values. The comparison stops as soon as a difference is found or one of the strings ends.
3. What's the difference between strcmp() and strcpy() in C?
While both strcmp() and strcpy() are built-in functions in C for handling strings, they serve different purposes. strcmp() is used to compare two strings lexicographically, and it returns an integer based on the comparison. On the other hand, strcpy() is used to copy one string into another. It doesn't perform any comparison but rather duplicates the contents of a string.
PAVAN VADAPALLI
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...