C ยท Chapter 20 of 45

C String Functions

The <string.h> header provides many useful functions for working with strings, such as measuring length, copying, concatenating and comparing them.

Because C strings are just char arrays, these functions rely on the null terminator to know where a string ends, so they can behave unpredictably on strings without one.

Syntax
#include <string.h>
strlen(s); strcpy(dest, src); strcat(dest, src); strcmp(s1, s2);

Common functions

strlen() returns the length of a string (excluding the null terminator). strcpy() copies one string into another, and strcat() appends one string onto the end of another.

Comparing strings

strcmp() compares two strings lexicographically, returning 0 if they are equal, a negative number if the first is 'less than' the second, and positive otherwise.

Example 1 (c)
#include <stdio.h>
#include <string.h>

int main() {
  char s[] = "Hello";
  printf("%lu\n", strlen(s));
  return 0;
}
Output
5

strlen counts the characters before the null terminator, not including it.

Example 2 (c)
#include <stdio.h>
#include <string.h>

int main() {
  char a[20] = "Hello, ";
  char b[] = "World!";
  strcat(a, b);
  printf("%s\n", a);
  return 0;
}
Output
Hello, World!

strcat appends b onto the end of a, so a's buffer must be large enough.

Key points

  • strlen() returns string length excluding the null terminator.
  • strcpy() and strcat() require the destination buffer to be big enough.
  • strcmp() returns 0 when two strings are equal.
  • All these functions require #include <string.h>.
๐Ÿ’ก Note: strcpy and strcat can overflow buffers if sizes aren't checked; safer alternatives like strncpy exist for this reason.

๐Ÿ“ Quick Quiz

1. What does strlen() count?

2. What does strcmp() return when two strings are equal?

3. Which header must be included to use strcpy?