Wednesday, November 25, 2015

Old School C String Compare

Even though i prefer C++ to C, sometimes it's good to know a little old school. Here's an example of how one can compare strings with C language. Since the C language does not have a string type, strings are built with arrays or pointers.

#include <stdio.h>
int main() {
  char * first_name = "John"; /* using pointer */
  char last_name[] = "Doe"; /* using local array */
  char name[100];
  /* comparing strings */
  if (strncmp(first_name, "John") != 0) return 1;
  if (strncmp(last_name, "Doe") != 0) return 1;
  sprintf(name, "%s %s", first_name, last_name);
  return 0;
}
To break it down a bit...
The first_name variable is set as a pointer, which means that we can view it but not alter it. The last_name variable is set as a local array, which means we can also alter it. We can alter the last_name in whole or in part since it is constructed as an array.

last_name[] = "Smith"; /* this would change the whole last name to `Smith` */
last_name[0] = "R"; /* this would change the first character in the last name, so that the last name becomes `Roe`  */
You may be asking yourself, why is the array bracket empty? Well,  it doesn't have to be. When it's left empty we allow the system to determine the number of characters. The thing to remember is that the number of characters will be one more than the string that you are defining. This is because in C you need to leave  room for string termination. Therefore...

char last_name[] = "Doe";
/* would be the same as */
char name[4] = "Doe";

The `strncmp` that we used to compare strings earlier could have taken on an additional  argument  - how many characters to compare. So that if we wanted to compare only the first three charaters of the first_name variable we could have done...

  if (strncmp(first_name, "Joh", 3) != 0) return 1;


No comments:

Post a Comment