Skip to main content
Logo image

Section 20.8 Alphabetize Strings

Similar to how we can sort numbers, strings can also be sorted (by alphabet.) The C string library provides help for doing so via the strcmp function. This function compares two strings and returns a negative number, zero or a positive number depending on which of the two strings comes first in the alphabet.
Here is how the function works: strcmp compares the two strings character by character. If the first character of two strings is equal, the next character of two strings are compared. This continues until the corresponding characters of the two strings are different or a null character ’\0’ is reached. Here is the return value of the function:
strcmp() returns
  • 0 if both strings are identical
  • a negative integer if the ASCII value of the first unmatched character is less than that of the second
  • a positive integer if the ASCII value of the first unmatched character is greater than that of the second
So if you compare "Hello" with "hello", what would strcmp() return? Use the code window below to look at a bunch of examples and really understand the function.