Welcome to our deep dive into the strncmp() function in C programming! This function is a powerful tool that helps compare two strings, and today, we'll explore its ins and outs.
The strncmp() function compares two strings, just like the strcmp() function. But unlike strcmp(), strncmp() only compares a specific number of characters, which makes it more flexible for certain scenarios.
Here's the syntax for the strncmp() function:
int strncmp(const char *str1, const char *str2, size_t n);Let's break this down:
str1 and str2: These are the two strings you want to compare.n: This is the maximum number of characters to compare. If the first n characters are different, strncmp() will return the result immediately, without comparing the rest of the strings.Now, let's look at some practical examples to help you understand better.
#include <stdio.h>
#include <string.h>
int main() {
char str1[50] = "Hello";
char str2[50] = "World";
int result = strncmp(str1, str2, 5);
if (result < 0)
printf("'%s' comes before '%s' in lexicographical order.\n", str1, str2);
else if (result > 0)
printf("'%s' comes after '%s' in lexicographical order.\n", str1, str2);
else
printf("'%s' is equal to '%s'.\n", str1, str2);
return 0;
}#include <stdio.h>
#include <string.h>
int main() {
char str1[50] = "Hello, World!";
char str2[10] = "World";
int result = strncmp(str1, str2, 5);
if (result < 0)
printf("Substring '%s' is not found in '%s'.\n", str2, str1);
else if (result == 0)
printf("Substring '%s' is found at the beginning of '%s'.\n", str2, str1);
else
printf("Substring '%s' is found inside '%s'.\n", str2, str1);
return 0;
}What does the `strncmp()` function do?
With this, we've covered the strncmp() function in C programming. Remember, it's a handy tool for comparing strings, especially when you only need to look at a specific number of characters. Happy coding! 🎉