GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing www.tutorialspoint.com — C++ cstring strncmp() Function
Selected Reading
C++ cstring strncmp() FunctionThe C++ cstring strncmp() function is used to compare two given strings. This function is similar to the strcmp() function but the difference is that strcmp() function compares two strings completely whereas strncmp() function compares only n number of characters of two strings. Assume that you have a string s1 and s2, and you want to compare only the first 5 characters of both strings. In this case, you can use the strncmp() function. SyntaxFollowing is the syntax of the C++ cstring strncmp() function − int strncmp(const char *str1, const char *str2, size_t n); ParametersParameters of the strncmp() function are below −
Return Values
Example 1Following is the basic example of the strncmp() function. In here, we will take two strings str1 and str2 and then compare only the first 5 characters of both strings using the strncmp() function. #include <iostream>
#include <cstring>
using namespace std;
int main() {
char str1[15];
char str2[15];
int ret;
strcpy(str1, "abcdef");
strcpy(str2, "ABCDEF");
ret = strncmp(str1, str2, 5);
if(ret > 0) {
cout << "str1 is greater than str2"<<endl;
} else if(ret < 0) {
cout << "str1 is less than str2"<<endl;
} else {
cout << "str1 is equal to str2"<<endl;
}
return 0;
}
OutputFollowing is the output of the above C++ program − str1 is less than str2 Example 2Now, Let's take another example where we will compare output of the strncmp() function with the strcmp() function. #include <iostream>
#include <cstring>
using namespace std;
int main() {
char str1[15];
char str2[15];
int ret;
strcpy(str1, "abcdef");
strcpy(str2, "abcdefgh");
ret = strncmp(str1, str2, 5);
if(ret > 0) {
cout << "strncmp: str1 is greater than str2"<<endl;
} else if(ret < 0) {
cout << "strncmp: str1 is less than str2"<<endl;
} else {
cout << "strncmp: str1 is equal to str2"<<endl;
}
ret = strcmp(str1, str2);
if(ret > 0) {
cout << "strcmp: str1 is greater than str2"<<endl;
} else if(ret < 0) {
cout << "strcmp: str1 is less than str2"<<endl;
} else {
cout << "strcmp: str1 is equal to str2"<<endl;
}
return 0;
}
OutputFollowing is the output of the above C++ program − strncmp: str1 is equal to str2 strcmp: str1 is less than str2 The difference in the output of the above program is because the strncmp() function compares only the first 5 characters of both strings whereas the strcmp() function compares both strings completely. Advertisements
|
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |