strncmp() - String Manipulation Function

How to compare characters of the two arrays in C++?


strncmp() manipulation function is used to compare two strings lexicographically until the characters differ or a null is encountered or when specified count is reached. It returns an integer value.


int * strncmp( char * str1, const char * str2, size_t count );

The following table lists the possible meanings for the value returned by "strncmp()"
Value Meaning
Less than Zero str1 is less than str2
Zero str1 is equal to str2
Greater than Zero str1 is greater than str2

Example :

#include <iostream.h>
#include <string.h>
int main()
char arr1[][20]={"apple","orange", "oyster", "anger"};
int i, j=0;
for (i=0 ; i<4; i++)
if (strncmp (arr1[i],"a",1)==0 )
cout << "Total words starting with a is::" << j << "\n";
return 0;

Result :

Total words starting with a is::2

In the above example, this manipulation function is used to compare the array string characters lexographically to find the number of words starting with "a".

C++ Tutorial

Ask Questions

Ask Question