How to Use the Strncmp Function in C++

The C++ strncmp function compares a specified number of bytes between two strings. It returns 0 if they are equal to each other and a nonzero value to indicate which string is greater. The following steps will help you use the function strncmp in C++.

Instructions

    • 1

      Learn the syntax of strncmp in C++. The complete syntax is int strncmp (const char *pointer1, const char *pointer2, size_t num);.

    • 2

      Notice that pointer1 and pointer2 are pointers to characters. strncmp starts at the beginning of each string and begins comparing characters until they differ or a null terminating character is read or num bytes have been compared. Strncmp returns a zero if all bytes match. Strncmp returns a positive integer if the first non-matching byte as an unsigned char is greater for pointer1; otherwise it returns a negative integer.

    • 3

      Understand that the C++ strncmp function is kept in the cstring library. You may need to include the string.h header file to use this function.

    • 4

      #include
      #include

      int main ()
      {
      char string1[][3] = { "archer" , "arrange" , "array" };
      int n;
      puts ("Looking for words beginning with arr...");
      for (n=0 ; n<3 ; n++)
      if (strncmp (string1[n],"arr",3) == 0)
      printf ("found %s\n",string1[n]);
      return 0;
      }

      Observe the following output for this program:

      Looking for words beginning with arr...
      found arrange
      found array

    • 5

      Observe the following output for this program:

      Looking for words beginning with arr...
      found arrange
      found array

      Notice that strncmp did not match "archer" with "arr" because we are comparing the first three characters.

Related Searches:

Resources

Comments

You May Also Like

Related Ads

Featured