C++ String strncmp() Function
Photo Credit to CodeToFun
đ Introduction
In C++ programming, comparing strings is a common operation, and the C++ Standard Library provides the strncmp()
function for this purpose.
This function allows you to compare substrings of two strings up to a specified length.
In this tutorial, we'll explore the usage and functionality of the strncmp()
function in C++.
đĄ Syntax
The signature of the strncmp()
function is as follows:
int strncmp(const char *str1, const char *str2, size_t n);
This function compares the first n characters of two C-style strings (str1 and str2).
đ Example
Let's delve into an example to illustrate how the strncmp()
function works.
#include <iostream>
#include <cstring>
int main() {
const char * str1 = "Hello, World!";
const char * str2 = "Hello, C++!";
// Compare the first 5 characters case-sensitively
int result = strncmp(str1, str2, 5);
// Output the result
if (result == 0) {
std::cout << "The substrings are equal.\n";
} else {
std::cout << "The substrings are not equal.\n";
}
return 0;
}
đģ Output
The substrings are equal.
đ§ How the Program Works
In this example, the strncmp()
function compares the first 5 characters of the strings "Hello, World!" and "Hello, C++!" and prints the result.
âŠī¸ Return Value
The strncmp()
function returns an integer less than, equal to, or greater than zero if the first n characters of str1 are found, respectively, to be less than, to match, or be greater than the first n characters of str2.
đ Common Use Cases
The strncmp()
function is useful when you need to compare substrings of two strings up to a specific length. It's commonly employed in scenarios where you want to check the equality of a portion of two strings.
đ Notes
- The comparison is case-sensitive. If you need a case-insensitive comparison, consider using strncasecmp() in POSIX systems or a custom case-insensitive comparison function.
đĸ Optimization
The strncmp()
function is optimized for efficient substring comparison. Ensure that the specified length n does not exceed the length of the shorter string to avoid undefined behavior.
đ Conclusion
The strncmp()
function in C++ is a versatile tool for comparing substrings of two strings up to a specified length. It provides a standardized and efficient way to perform substring comparisons, enhancing the flexibility of your code.
Feel free to experiment with different strings and explore the behavior of the strncmp()
function in various scenarios. Happy coding!
đ¨âđģ Join our Community:
Author
For over eight years, I worked as a full-stack web developer. Now, I have chosen my profession as a full-time blogger at codetofun.com.
Buy me a coffee to make codetofun.com free for everyone.
Buy me a Coffee
If you have any doubts regarding this article (C++ String strncmp() Function), please comment here. I will help you immediately.