strcmp() Function 🎯Welcome back to CodeYourCraft! Today, we're going to delve into the world of string comparison in C programming, focusing on the strcmp() function. This function is a cornerstone of string manipulation, and it's essential for anyone looking to become a proficient C programmer. So, let's get started!
strcmp() Function? 📝The strcmp() function is a built-in library function in C that compares two strings lexicographically (i.e., character by character). It returns an integer indicating the lexicographical order of the two strings.
strcmp() Function? 💡The syntax for using the strcmp() function is as follows:
int strcmp(const char *str1, const char *str2);Here, str1 and str2 are the two strings you want to compare. The function returns the following:
str1 comes after str2 in lexicographical order.str1 comes before str2 in lexicographical order.Let's write a simple program to compare two strings:
#include <stdio.h>
int main() {
char str1[] = "Hello";
char str2[] = "World";
int result;
result = strcmp(str1, str2);
if (result > 0) {
printf("%s comes after %s\n", str1, str2);
} else if (result < 0) {
printf("%s comes before %s\n", str1, str2);
} else {
printf("%s and %s are identical\n", str1, str2);
}
return 0;
}When you run this program, it will output:
Hello comes before World
strcmp() is case-sensitive, meaning it differentiates between uppercase and lowercase characters.str1 and str2 should be null-terminated strings. In C, this means that the last character of the string should be \0.What does the `strcmp()` function do in C programming?
In addition to comparing strings, you can also use the strcmp() function to determine the length of a string. This is because strcmp() stops comparing when it encounters a null character (\0). Here's an example:
#include <stdio.h>
int main() {
char str[] = "Hello, World!";
int length = 0;
while (str[length] != '\0') {
length++;
}
printf("The length of the string is: %d\n", length);
return 0;
}When you run this program, it will output:
The length of the string is: 13
That's it for today's lesson! We hope you found this explanation of the strcmp() function helpful. Stay tuned for more in-depth lessons on C programming here at CodeYourCraft. Happy coding! 💻🌟