What does strcmp Do in C?
strcmp is a built-in function in C programming language that compares two strings and returns an integer indicating the relative positions of the strings. It is often used to find the minimum or maximum value of two strings. In this article, we will explore the functionality of strcmp and provide examples of its usage.
Overview of strcmp
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
int strcmp(const char *str1, const char *str2);
The strcmp function takes two const char* parameters, which are the addresses of the strings to be compared. The function returns an int value that indicates the relative position of str1 to str2.
Return Value
The strcmp function returns one of the following values:
- 0: If the strings are equal.
- -1: If
str1is lexicographically less thanstr2. - 1: If
str1is lexicographically greater thanstr2.
Here is a breakdown of the possible return values:
| Return Value | Description |
|---|---|
| 0 | The strings are equal. |
| -1 | str1 is lexicographically less than str2. |
| 1 | str1 is lexicographically greater than str2. |
Comparing Strings
To compare two strings, we can use the following steps:
- Initialize two pointers,
iandj, to the beginning ofstr1andstr2, respectively. - Compare the characters at the current positions of
iandj. If the characters match, move both pointers forward. - If the characters do not match, compare the next characters and repeat the process until one of the strings is exhausted.
- If
iis not exhausted and the character atiis less than the character atj, moveiforward. Ifiis exhausted and the character atiis greater than the character atj, movejforward. - Repeat the process until
iis exhausted orjis exhausted.
Here is an example implementation of strcmp:
#include <stdio.h>
int strcmp(const char *str1, const char *str2) {
while (*str1 && *str2) {
if (*str1 < *str2) {
return -1;
} else if (*str1 > *str2) {
return 1;
}
str1++;
str2++;
}
if (*str1 == *str2) {
return 0;
} else if (*str1 < *str2) {
return -1;
} else {
return 1;
}
}
Example Usage
Here is an example of how to use strcmp:
#include <stdio.h>
int main() {
char str1[] = "hello";
char str2[] = "world";
char str3[] = "abc";
printf("strcmp('%s', '%s') = %dn", str1, str2, strcmp(str1, str2));
printf("strcmp('%s', '%s') = %dn", str1, str3, strcmp(str1, str3));
printf("strcmp('%s', '%s') = %dn", str2, str2, strcmp(str2, str2));
return 0;
}
This will output:
strcmp('hello', 'world') = -1
strcmp('hello', 'abc') = 1
strcmp('world', 'abc') = 1
In summary, the strcmp function is a simple implementation of the string comparison function in C. It returns an int value indicating the relative position of two strings. It can be used to compare strings and find the minimum or maximum value of two strings.
