C String Functions

Working with strings by hand is possible, but C ships with a helpful library called string.h that does the common jobs for you. It includes ready-made functions to measure a string's length, copy one string into another, join two strings, and compare two strings. Include string.h at the top of your file to use them.

Finding the Length with strlen

The strlen function counts how many characters are in a string, not counting the null terminator. This is different from sizeof, which counts the full array including the terminator and any unused space.

Using strlen

#include <stdio.h>
#include <string.h>

int main() {
  char name[] = "Anna";
  printf("Length: %lu\n", strlen(name));
  return 0;
}
Note: strlen returns 4 for "Anna" because it counts only the visible letters. sizeof(name) would return 5 because it also counts the null terminator.

Copying and Joining Strings

You cannot copy a string with a simple equals sign in C. Use strcpy to copy one string into another, and strcat to attach one string onto the end of another. Both need the destination array to be large enough to hold the result.

strcpy and strcat

#include <stdio.h>
#include <string.h>

int main() {
  char full[20];
  strcpy(full, "Hello");
  strcat(full, " World");
  printf("%s\n", full);
  return 0;
}

Comparing Strings

To check whether two strings are the same, use strcmp. It returns 0 when the strings match exactly. It returns a negative or positive number when they differ, based on which string comes first alphabetically.

Using strcmp

#include <stdio.h>
#include <string.h>

int main() {
  char a[] = "apple";
  char b[] = "apple";
  if (strcmp(a, b) == 0) {
    printf("The strings are equal\n");
  } else {
    printf("The strings are different\n");
  }
  return 0;
}

Common string.h functions

FunctionWhat it does
strlen(s)Returns the number of characters in s
strcpy(dest, src)Copies src into dest
strcat(dest, src)Adds src to the end of dest
strcmp(a, b)Returns 0 if a and b are equal
Note: A common bug is comparing strings with == instead of strcmp. Using == compares memory addresses, not the actual text, so it usually gives the wrong answer.