strcmp()

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;.

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
Loading...

Contributors

Interested in helping build Docs? Read the Contribution Guide or share your thoughts in this feedback form.

Learn C++ on Codecademy