C++ strcmp()

Christine_Yang's avatar
Published Aug 13, 2022Updated Dec 21, 2022
Contribute to Docs

The strcmp() function compares two strings and returns an integer value.

Note: strcpy() only works on C-style strings of type char str[];, not C++ style strings of type string str;.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.
    • Beginner Friendly.
      11 hours

Syntax

#include <string.h>

strcmp(string1, string2);

At the top of the file, the <string.h> header file needs to be included. The strcmp() function compares C-style strings string1 and string2 and returns an integer value.

  • If the two strings are the same, it returns 0.
  • If string1 > string2, it returns a positive value.
  • If string1 < string2 or string1 is a substring of string2, it returns a negative value.

Codebyte Example

The following performs comparisons on three strings and prints out information about their order:

Code
Output

All contributors

Contribute to Docs

Learn C++ on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.
    • Beginner Friendly.
      11 hours