Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 135 ยท Arrays and Strings

String Functions

A practical tour of string.h - strlen, strcpy and strcat, strcmp, strchr and strstr, strspn, memcpy, memmove and memset, and splitting text with strtok.

Because C strings are just char arrays ending in '\0', you can't copy them with = or compare them with ==. Instead, the standard header <string.h> provides a library of functions for copying, joining, comparing, searching and splitting text, plus a family of mem functions that work on raw bytes of any kind.

You'll use these functions in almost every C program, so it pays to know them precisely: what each returns, what it assumes about its arguments, and which ones can overflow a buffer. This lesson tours the whole header, grouped by job, with runnable examples. The rules for using the risky ones safely get a lesson of their own next: Safe String Handling.

Length: strlen

size_t strlen(const char *s) returns the number of characters before the terminating '\0'. You met it in Strings. Remember three facts:

  • It counts bytes, not visible characters (UTF-8 letters can take several bytes).
  • It scans the string every time you call it, so it costs time proportional to the length. Don't put it in a loop condition: for (size_t i = 0; i < strlen(s); i++) rescans s on every iteration. Call it once and save the result.
  • s must point at a properly terminated string. strlen(NULL) is undefined behavior (usually a crash).

Copying and joining: strcpy and strcat

strcpy(dest, src) copies the string src, terminator included, into the array dest. strcat(dest, src) appends src to the end of the string already in dest. Both return dest.

Neither function knows how big dest is. They write until the source's terminator, so you must guarantee that the destination has room. The professional habit is to check the lengths first:

C Building a path with strcpy and strcat

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

It prints path: /home/mira/notes.txt (20 chars) and then too long for 32 bytes. The check needed > capacity is what makes strcpy and strcat safe here. Without it, the second call would write 42 bytes into a 32-byte array.

Note one more cost of strcat: to append, it first scans dest to find its end. Appending many pieces one by one to a growing string rescans everything each time. When you know where the end is, copy there directly (with memcpy at dest + length), or build the whole string in one snprintf call. Safe String Handling shows both.

strncpy and strncat

The "n" versions take a count, which sounds like a fix but each has a twist:

  • strncpy(dest, src, n) copies at most n characters. If src is shorter, it pads the rest of the n bytes with zeros. If src is n characters or longer, it copies exactly n and adds no terminator. It was designed for fixed-width record fields, not for safe copying.
  • strncat(dest, src, n) appends at most n characters of src and always adds a terminator. The catch is that n counts characters to append, not the size of dest, so the correct call is strncat(dest, src, sizeof dest - strlen(dest) - 1).

Both are easy to misuse, which is why the next lesson recommends snprintf instead.

Comparing: strcmp and strncmp

int strcmp(const char *a, const char *b) compares two strings character by character, as unsigned char values, until they differ or both end. It returns:

  • a negative number if a comes first,
  • zero if the strings are equal,
  • a positive number if b comes first.

Only the sign is guaranteed, never a specific value like -1. strncmp(a, b, n) does the same but looks at no more than n characters, which makes it perfect for checking prefixes.

C Comparing strings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The output:

TEXT
apple  is before  apricot
zebra  is after   Zebra
car    is before  carpet
10     is before  9
same   is same as same
'--verbose=2' starts with --verbose
typed == "yes": false, strcmp: equal

The comparisons are byte-wise, which leads to the surprises above: every uppercase ASCII letter sorts before every lowercase one, and "10" comes before "9" because '1' is less than '9'. For human-friendly ordering you need your own comparison (case-insensitive, or numbers compared as numbers). POSIX systems provide strcasecmp for case-insensitive comparison, but it isn't part of standard C; strcoll compares according to the current locale.

strcmp returns 0 for equal strings, which is false in a condition. if (strcmp(answer, "yes")) runs when the strings are different. Always write the comparison out: if (strcmp(answer, "yes") == 0).

Searching

<string.h> has a search function for every common question. They all return a pointer into the original string (or NULL when nothing is found), so you can compute positions by subtracting the start, or continue searching from the match.

Function Finds
strchr(s, c) first occurrence of character c
strrchr(s, c) last occurrence of character c
strstr(s, sub) first occurrence of the substring sub
strpbrk(s, set) first character that is any of the characters in set
strspn(s, set) length of the initial run made only of characters in set (returns size_t)
strcspn(s, set) length of the initial run containing none of the characters in set (returns size_t)
C Searching inside strings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

It prints:

TEXT
name: summary.final.pdf, extension: pdf
top folder: reports
'the' appears 3 times
key: 'timeout', value: '30s'
number part: 4471

%.*s with a length is the trick for printing part of a string without copying it. And the found pointers point into the original data, so if that data is a modifiable array, you can even write through them. strchr also finds the terminator itself if you search for '\0', which is a quick way to get a pointer to the end of a string.

There's a quirk in the signatures: these functions take a const char * but return a plain char *, so they silently drop the const. Don't use the result to modify a string literal. (C23 turns them into type-generic macros that return const char * when given one, so C libraries that implement this can catch the mistake.)

The mem functions: raw bytes

The mem functions work on any bytes, not just text. They ignore '\0' completely and always take an explicit count. That makes them suitable for arrays of numbers, structs, and binary data.

Function What it does
memcpy(dest, src, n) copy n bytes; source and destination must not overlap
memmove(dest, src, n) copy n bytes; correct even if they overlap
memset(dest, value, n) set n bytes to value (converted to unsigned char)
memcmp(a, b, n) compare n bytes; negative, zero or positive like strcmp
memchr(s, c, n) find byte c in the first n bytes
C memcpy, memmove, memset and memcmp

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

It prints the backup 1 2 3 4 5 6 7 8, then 1 2 99 3 4 5 6 7 after the insert, then eight zeros, memcmp backup vs data: different, and Hello, world.

Keep these rules in mind:

  • Counts are in bytes. Copying 5 ints means 5 * sizeof data[0] bytes, not 5. Using sizeof of the array or of an element keeps this right.
  • Overlap needs memmove. Shifting elements within the same array, as in the insert above, overlaps source and destination. memcpy is allowed to assume no overlap and may produce garbage; memmove handles it.
  • memset sets bytes, not values. memset(data, 0, ...) gives zeros, and memset(data, -1, ...) gives -1 in every int because all bits become 1, but memset(data, 1, ...) makes each 4-byte int equal to 16843009 (0x01010101), not 1. Use a loop to fill with other values.
  • Don't memcmp structs to compare them: padding bytes between members can contain anything. See Padding and Alignment.
  • The delete trick copies strlen(...) + 1 bytes so the terminator moves too.

Splitting text: strtok

strtok splits a string into tokens separated by any of a set of delimiter characters. It's used in two steps: the first call passes the string, and later calls pass NULL to continue where the previous call stopped. Each call returns a pointer to the next token, or NULL when there are no more.

C Splitting with strtok

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The output:

TEXT
word 1: split
word 2: this
word 3: sentence
word 4: into
word 5: words
field 1: 'Lin'
field 2: 'Berlin'
record is now: 'Lin'

strtok is convenient for simple jobs like splitting a command into words, but it has serious limits that you need to know:

  • It modifies its input. It writes '\0' over each delimiter it finds, so it can't be used on string literals or on data you need to keep intact. Pass a copy if necessary.
  • It merges runs of delimiters and skips empty fields. For CSV-like data where "Lin,,Berlin" has an empty middle field, strtok gives the wrong answer. Use strcspn in a loop, or POSIX strsep, to keep empty fields.
  • It keeps hidden state between calls (a static pointer to where it stopped). You can't tokenize two strings at once, for example splitting lines and then words inside each line, and it isn't safe to use from several threads. POSIX strtok_r and C11's optional strtok_s take the state as an extra argument and fix both problems.

Duplicating: strdup and strndup

C23 added two functions that POSIX systems have had for decades:

C
char *copy = strdup(original);          // malloc'd copy of the whole string
char *prefix = strndup(original, 5);    // malloc'd copy of at most 5 characters
if (copy == NULL || prefix == NULL) { /* out of memory */ }
...
free(copy);
free(prefix);

They allocate exactly enough memory with malloc, copy the text and terminate it. They return NULL if allocation fails, and you must free the result. Dynamic Memory covers allocation in detail.

C libraries older than C23, including the one on our server, only declare these functions when you ask for POSIX features. In strict -std=c23 mode you'd get "implicit declaration of function 'strdup'". Defining a feature-test macro before the first #include fixes it: #define _POSIX_C_SOURCE 200809L. Safe String Handling has a runnable example.

Quick reference

Job Function Bounded?
length strlen reads until '\0'
copy strcpy, strncpy, memcpy, memmove strcpy no; others take a count
append strcat, strncat strcat no
compare strcmp, strncmp, memcmp n versions yes
find character strchr, strrchr, memchr memchr takes a count
find substring strstr reads until '\0'
character classes strspn, strcspn, strpbrk reads until '\0'
fill memset takes a count
split strtok (strtok_r on POSIX) modifies the input
duplicate strdup, strndup (C23) allocates

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does strcmp("Zoo", "apple") return?

    strcmp compares byte values. In ASCII, all uppercase letters (65 to 90) come before lowercase ones (97 to 122), so "Zoo" sorts first.
  2. 2. You need to shift elements to the right inside the same array. Which function is correct?

    Source and destination overlap. memcpy may assume they don't, which gives wrong results; memmove is defined to handle overlap.
  3. 3. After int a[4]; memset(a, 1, sizeof a);, what is a[0] on a system with 4-byte ints?

    memset sets every byte to 1, so each int contains the bytes 01 01 01 01. Only 0 (and -1) give the "expected" value; use a loop to fill with other numbers.
  4. 4. How many tokens does strtok return for "red,,blue," with the delimiter ","?

    strtok treats consecutive delimiters as one separator and ignores leading and trailing ones, so it returns only "red" and "blue". Empty fields are lost.
  5. 5. What does strcspn("width: 40px", ":") return?

    strcspn counts the initial characters that are not in the set. "width" has 5 characters before the ':'.

Summary

  • strlen counts bytes before '\0' and rescans the string on every call.
  • strcpy and strcat don't know the destination size; check lengths first. strncpy may omit the terminator and strncat's count is not the buffer size.
  • strcmp and strncmp compare bytes and return negative, zero (equal) or positive; never compare strings with ==.
  • strchr, strrchr, strstr, strpbrk, strspn and strcspn answer search questions and return pointers or lengths into the original string.
  • The mem functions work on raw bytes with explicit counts: memcpy (no overlap), memmove (overlap OK), memset (byte values), memcmp.
  • strtok splits text but modifies its input, skips empty fields and keeps hidden state; prefer strtok_r or strcspn loops for real parsing.
  • C23 adds strdup and strndup, which return malloc'd copies you must free.

Next: Safe String Handling, where you'll learn to prevent buffer overflows for good.