strncmp

Compares not more than maxchar characters of two ASCII character strings and returns a negative, 0, or positive integer, indicating that the ASCII values of the individual characters in the first string are less than, equal to, or greater than the values in the second string.

Format

#include  <string.h>

int strncmp  (const char *str_1, const char
             *str_2, size_t maxchar);

Arguments

str_1, str_2
Pointers to character strings.
maxchar
The maximum number of characters (beginning with the first) to search in both str_1 and str_2. If maxchar is 0, no comparison is performed and 0 is returned (the strings are considered equal).

Description

This function compares no more than maxchar characters from the string pointed to by str_1 to the string pointed to by str_2. The strings are compared until a null character is encountered, the strings differ, or maxchar is reached. Characters that follow a difference or a null character are not compared.

Return Values
< 0  Indicates that str_1 is less than str_2
= 0  Indicates that str_1 equals str_2
> 0  Indicates that str_1 is greater than str_2

Examples

  1. #include <string.h>
    #include <stdio.h>
    
    $ create tmp.c
        main()
        {
            printf( "%d\n", strncmp("abcde", "abc", 3));
        }
        $ cc tmp.c
    
    When linked and executed, this example returns 0, because the first 3 characters of the 2 strings are equal:
    $ run tmp
            0
    
  2. #include <string.h>
    #include <stdio.h>
    
    $ create tmp.c
        main()
        {
            printf( "%d\n", strncmp("abcde", "abc", 4));
        }
        $ cc tmp.c
    
    When linked and executed, this example returns a value greater than 0 because the first 4 characters of the 2 strings are not equal (The "d" in the first string is not equal to the null character in the second):
    $ run tmp
            100
    


Previous Page | Next Page | Table of Contents | Index