Monday, May 2, 2011

How Does Strcmp work !


1. What is Strcmp?
- Strcmp stands for String Compare, and all it does is compare 2 strings.

2. How does it work
- strcmp works by taking each characters of a string, and substract it's ASCII-Code with the ASCII-Code of the character in the other string. So lets say you want to compare the string "samp" with the string "samp". This is what strcmp will do:
- Take the first character ('s') and substract it with the character from the second string ('s')
- If the characters are the same, the result of the substraction will be 0 (null)
- Do this for all characters of the strings

If the 2 strings are the same, the total of all the characters substracted from eachother will be 0.
This is why to compare 2 strings you need to check if the result is 0, not 1.

Example:
if(strcmp("Hello", "Hello") == 0)
{
    // Do something if they the same
}
else
{
    // Do something if they are different from another
}

If the 2 strings are not equal to eachother, strcmp will return the result from the substractions.

No comments:

Post a Comment