strncmp function(Bounded String Compare) in C Language – example and detail

In the C Programming Language, the strncmp feature returns a negative, zero, or high quality integer depending on whether or not the first n characters of the object pointed to via s1 are much less than, equal to, or greater than the first n characters of the object pointed to through s2.

The strncmp characteristic will give up comparing if a null persona is encountered in either s1 or s2.

Syntax

The syntax for the strncmp function in the C Language is:

int strncmp(const char *s1, const char *s2, size_t n);

Parameters or Arguments

s1 An array to compare. s2 An array to compare. n The variety of characters to compare.

Returns

The strncmp function returns an integer. The return values are as follows:

Return Value Explanation 0 s1 and s2 are equal Negative integer The stopping personality in s1 was once less than the stopping persona in s2 Positive integer The stopping personality in s1 was once larger than the stopping character in s2

Required Header

In the C Language, the required header for the strncmp characteristic is:

#include <string.h>

Applies To

In the C Language, the strncmp function can be used in the following versions:

ANSI/ISO 9899-1990

strncmp Example

Let’s seem to be at an instance to see how you would use the strncmp function in a C program:

/* Example using strncmp by TechOnTheNet.com */

#include <stdio.h>
#include <string.h>

int main(int argc, const char * argv[])
{
    /* Create a place to store our results */
    int result;

    /* Create two arrays to hold our data */
    char example1[50];
    char example2[50];

    /* Copy two strings into our data arrays */
    strcpy(example1, "C strncmp at TechOnTheNet.com");
    strcpy(example2, "C strncmp is a string function");

    /* Compare the two strings provided up to 11 characters */
    result = strncmp(example1, example2, 11);

    /* If the two strings are the same say so */
    if (result == 0) printf("Strings are the same\n");

    /* If the first string is less than the second say so
     (This is because the 'a' in the word 'at' is less than
     the 'i' in the word 'is' */
    if (result < 0) printf("Second string is less than the first\n");

    return 0;
}

When compiled and run, this software will output:

Second string is less than the first

Similar Functions

Other C functions that are similar to the strncmp function:

memcmp characteristic strcmp feature strcoll feature