Jump to content

strcmp() function returns a negative number if...

- - - - -

  • Please log in to reply
1 reply to this topic

#1
jackson6612

jackson6612

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 304 posts
Hi :)

The quoted text is from a book. I need to confirm this. Suppose the two strings are: "Hello there" (first string), "John Adams" (second string). According to the text, if the "first string" appears before the second string then a -ve number will be returned and first string is considered to be less. So, in case of our supposed strings if we write strcmp(first string, second string) a negative number will be returned. Correct? Thanks for your help.


Quote

The operator==() function uses the library function strcmp() to compare the two C-strings. This function returns 0 if the strings are equal, a negative number if the first is less than the second, and a positive number if the first is greater than the second. Here less than and greater than are used in their lexicographical sense to indicate whether the first string appears before or after the second in an alphabetized listing.

I'm an outright beginner, learning C++. Using Win XP Pro and Code::Blocks. Be nice to me, please.:)

#2
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,118 posts
  • Location:Vancouver, Eh! Cleverness: 200
You can simply picture an exhaustive dictionary, with every possible combination of printable ASCII letters.

Now if you compare "bbb" and "abb", abb is an "a" word and comes far before in the dictionary and will return +1. (it is in positive position to "abb")

If "abb", and "abb" were compared, are they in the same relative position? Yes, so zero is returned (they are lexicographically zero places from each other)

In comparing "aaa" and "aaaa", "aaaa" is down more in the list and will return -1. aaaa, remember, comes before aaab, or aab in the dictionary.

A little side note, a good reason why it does not just return true or false, is that you can create an alphabetic sorting function that uses the -1 and +1 values to move a word to a different position on a list with relative ease.

Alexander.
Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users