In the C programming language, the strcmp function is commonly used for comparing two strings and is part of the string.h header. The function's return value indicates the relationship between the two strings, providing an integer value for lexicographical comparison purposes.
Syntax:
It has the following syntax.
int strcmp(const char *str1, const char *str2);
In this specified syntax:
- str1: Represents the initial string for comparison purposes.
- str2: Denotes the secondary string for the purpose of comparison.
Return Value:
The function output is an integer indicating the comparison result of the two strings:
- <0: The str1 is lexicographically less than str2.
- ==0: The str1 is equal to str2.
- > 0: Indicates that str1 is greater in lexicographical order than str2.
Simple C strcmp function Example
Let's consider an example to showcase the strcmp function in the C programming language.
Example
#include <stdio.h>
#include <string.h>
int main() { //main function
char str1[] = "hello";
char str2[] = "hello";
int result = strcmp(str1, str2);
if (result == 0)
printf("Strings are equal.\n");
else
printf("Strings are not equal.\n");
return 0;
}
Output:
Strings are equal.
Explanation:
In this instance, we are examining two variables, str1 and str2, which hold identical text "hello". Subsequently, the comparison between these two strings is performed using the strcmp function. Since there is a complete match between all characters in the strings, the strcmp function yields a return value of 0, indicating that the strings are indeed identical.
C Example to Compare Two Strings Lexicographically Using the strcmp Function
Let's consider an example to showcase the comparison of two strings in lexicographical order using the strcmp function in the C programming language.
Example
#include <stdio.h>
#include <string.h>
int main() { //main function
char a[] = "apple";
char b[] = "banana";
int res = strcmp(a, b);
if (res < 0)
printf("\"%s\" comes before \"%s\"\n", a, b);
else if (res > 0)
printf("\"%s\" comes after \"%s\"\n", a, b);
else
printf("Strings are equal.\n");
return 0;
}
Output:
"apple" comes before "banana"
Explanation:
In this instance, we've selected two strings, "apples" and "banana". Subsequently, we've employed the strcmp function, which produces a negative value as 'a' ("apple") precedes 'b' (in "banana") in the ASCII sequence. Thus, the outcomes guarantee the lexicographic sequence. It presents the strings that appear first according to the output value. In case the strings are identical, it indicates that the strings are equal.
C Example to Compare Two User-Input Strings Using the strcmp Function
Let's consider an example to illustrate how to compare two strings entered by users by utilizing the strcmp function in the C programming language.
Example
#include <stdio.h>
#include <string.h>
int main() { // main function
char str1[50], str2[50];
printf("Enter the first string: ");
fgets(str1, sizeof(str1), stdin);
printf("Enter the second string: ");
fgets(str2, sizeof(str2), stdin);
// Remove newline character added by fgets
str1[strcspn(str1, "\n")] = '\0';
str2[strcspn(str2, "\n")] = '\0';
if (strcmp(str1, str2) == 0)
printf("Strings are equal");
else
printf("Strings are not equal");
return 0;
}
Output:
Enter the first string: hello
Enter the second string: hello
Strings are equal
Explanation:
In this instance, we've generated two strings that capture user input utilizing the fgets function. Subsequently, we've employed the strcmp function to contrast the two strings. A return value of zero (0) indicates identical strings; alternatively, a non-zero value signifies a variance. To conclude, the program displays the outcome of the string comparison, determining their equality status.
Features of the strcmp function in C
The strcmp function has several features in the C programming language. Some of them are as follows:
- The strcmp function in C is commonly utilized to compare two null-terminated strings character by character.
- The comparison of the strings in C is case-sensitive, which means that the text "Hello" and "hello" are considered different.
- We can handle non-alphabetic characters correctly using the strcmp function as long as the strings are null-terminated.
- It doesn't change the actual string during comparison.
- The comparison of strings is based on the ASCII values of the characters, which determines the lexicographical order.
- The strcmp function will halt comparison when it hits the first difference or reaches the end of a string.
Conclusion
In summary, the strcmp function plays a fundamental role in string manipulation within the C programming language. It allows for the comparison of two strings in a resourceful way, determining their order based on ASCII character values.
The strcmp function offers enhanced management of string comparisons. By analyzing characters individually, it proves valuable for tasks like comparing equality, validating input, and implementing sorting algorithms. Nonetheless, it operates in a case-sensitive manner and may behave unexpectedly if strings lack proper null termination.
C Strcmp Function Frequently Asked Questions
1) What value does the strcmp function return, and what is its functionality in the C programming language?
The strcmp function is a method that provides an integer result based on comparing two strings. If the strings are identical, it returns 0. If the first string is alphabetically before the second, it gives a negative integer. Conversely, if the first string is alphabetically after the second, it returns a positive value. This function compares each character by its ASCII value until a deviation is identified or a null terminator is reached.
2) Is the strcmp function case sensitive?
Yes, the strcmp function is highly precise as it distinguishes characters based on their ASCII values. Uppercase letters like A to Z (65-90) have lower ASCII values compared to lowercase letters like a to z (97-122). In C, string comparison is case-sensitive, so "Hello" and "hello" are recognized as distinct strings.
When NULL is passed to the strcmp function in C, it will result in undefined behavior. This is because the strcmp function expects valid C-style strings as arguments, and passing NULL violates this requirement, leading to unpredictable outcomes. It is crucial to always provide valid string pointers to the strcmp function to ensure proper functionality and avoid potential issues.
When NULL is supplied to the strcmp function, it may result in undefined behavior as the function tries to access the memory addresses of the strings. If one or both pointers are NULL, it can potentially cause a segmentation fault leading to a crash. It is crucial to validate the pointers for accuracy before passing them to the strcmp function.
4) How does the strcmp function manage strings with varying lengths?
When both strings share the same initial characters but have different lengths, the strcmp function considers the shorter string as less than the longer one. This occurs because the function compares the strings character by character until a disparity is encountered or until one string concludes. Upon reaching the null terminator of the shorter string during comparison, the function concludes that it is of lesser value than the longer string.
The primary distinction between the strcmp and strncmp functions in C lies in the way they compare strings. While strcmp compares entire strings, strncmp allows for a specified number of characters to be compared within the strings.
The primary contrast between the strcmp and the strncmp functions lies in their comparison approach. While the strcmp function evaluates complete strings, the strncmp function specifically checks the initial n characters of both strings. This targeted comparison feature of the strncmp function serves as a protective measure against buffer overflows, especially in scenarios involving fixed-size arrays or incompletely populated strings.