Tuesday, June 2, 2009


How to Compare Two Strings in C Programming


from wikiHow - The How to Manual That You Can Edit

This describes an easy way to compare two strings in C programming.

Steps


  1. include
  2. char *string1, *string2;
  3. int someSaneCharLimit = 512; /*insert your own sane char limit here*/
  4. [Populate your strings however you wish]
  5. int i = strncmp(string1, string2, someSaneCharLimit);
  6. If i > 0, string1 > string2; If i <> string1; If i == 0, string1 == string2


Tips


  • The someSaneCharLimit parameter tells strncmp the maximum number of characters to examine. Using strncmp instead of the original strcmp (as well as the other strn* routines vs. their str* counterparts) is one of the many ways that C programs can be made more stable and secure.
  • You may put this in an "if" statement.
  • For one string to be 'less than' another means it is lexicographically less than. In layman's terms it means it would come before the other 'word' in a dictionary.
  • With strncmp you only check the first someSaneCharLimit number of characters. If they are the same up to that point (no matter what comes after that) they will be equal i.e. strncmp("abcxyz", "abchij", 3) would return a 0 whereas strncmp("abcxyz", "abchij", 6) would return a number greater than 0.


Warnings


  • Remember that the return value is 0 if the strings are the same. This could confuse you because 0 is also the value of FALSE.


Related wikiHows





Article provided by wikiHow, a wiki how-to manual. Please edit this article and find author credits at the original wikiHow article on How to Compare Two Strings in C Programming. All content on wikiHow can be shared under a Creative Commons license.