C String Functions: How They Work and When to Use Them

Formulas & functions · Updated November 22, 2026

C string functions are standard library routines declared in <string.h> for measuring, copying, comparing, joining, and searching strings. They operate on character sequences that end with a null character, so choosing the right function also means ensuring the destination has enough space and the input is properly terminated.

How C Strings Work

C does not have a built-in string type. A string is usually a sequence of characters stored in a char array, followed by the null character '\0', which marks where the text ends. For example, the literal "cat" occupies four bytes: three for the letters and one for the terminator. A string function usually receives a pointer to the first character and finds the end by scanning for that terminator.

This representation is different from a length-prefixed string, where the length is stored alongside the data. A C string function such as strlen does not know an array’s capacity; it only searches for '\0'. If a character array lacks a terminator, functions that expect a string can read beyond its bounds, causing undefined behavior. Include <string.h> for the standard string functions, and remember that the header declares functions rather than creating a string data type.

Common Functions for Measuring and Copying

The most frequently used functions include strlen for length, strcpy and strncpy for copying, and strcat and strncat for appending. Their names are similar, but their behavior and requirements differ:

  • strlen(s) returns the number of characters before the first null character. It does not count the terminator.
  • strcpy(destination, source) copies the source, including its terminator. The destination must have room for all of it.
  • strncpy(destination, source, n) copies at most n characters, padding with null characters if the source is shorter. If the source has at least n characters, the result might not be terminated.
  • strcat(destination, source) appends the source to the existing destination string, including the final terminator. The destination must already be a valid string and have enough remaining space.
  • strncat(destination, source, n) appends at most n source characters, then adds a terminator. The size argument limits source characters, not the total destination capacity.

For example, if source contains "red", a destination array needs at least four bytes for a copy. If it already contains "blue", appending "red" needs eight bytes total: four for "blue", three for "red", and one for the terminator. A common mistake is to allocate space based only on the new text.

Comparing Strings Correctly

Use strcmp(a, b) to compare two null-terminated strings, or strncmp(a, b, n) to compare no more than the first n characters. These functions return an integer less than zero, equal to zero, or greater than zero, depending on the ordering. The exact nonzero value is not specified, so test the sign or equality rather than expecting a particular result such as -1.

String comparison is not the same as testing whether two pointers refer to the same address. In an expression such as a == b, pointer values are compared; the characters are not. To test whether two strings contain the same sequence, use strcmp(a, b) == 0. The standard comparison is based on character values, not human-language dictionary rules. It does not automatically ignore case, normalize accents, or sort words according to a locale. Functions such as strcasecmp are available on some systems but are not part of the ISO C standard.

Searching and Tokenizing Text

strchr(s, c) searches for the first occurrence of a character, while strrchr(s, c) finds the last. Both return a pointer to the matching character or a null pointer if there is no match. strstr(s, substring) locates the first occurrence of a substring. The returned pointer points into the original string; it does not create a copy. For instance, searching for "day" in "Monday" returns a pointer to the d in that existing array.

strtok breaks a mutable string into tokens using characters from a delimiter set. It replaces delimiters in the input with null characters and keeps internal state between calls, so it changes the original data and is awkward for nested parsing or concurrent use. The C standard library also provides strtok_s in the optional Annex K bounds-checking interface, but support for Annex K is not universal. For parsing complex formats, explicit scanning or a dedicated parser is often clearer and less error-prone.

Lengths, Bytes, and Multibyte Text

strlen counts bytes before '\0', not necessarily visible characters. In ASCII text, a letter normally occupies one byte, so the distinction is easy to miss. In UTF-8, a character such as an accented letter or many symbols can use multiple bytes. Consequently, strlen may report a larger number than the number of characters a person sees. It also cannot tell whether a byte sequence is valid UTF-8.

For a buffer that may contain arbitrary binary data, use a separately tracked length and byte-oriented operations such as memcpy, memcmp, and memchr, also declared in <string.h>. These functions take explicit byte counts and do not stop at null bytes. Do not pass binary data to ordinary string routines unless it is deliberately represented as a terminated text string. C also has wide-character functions such as wcslen in <wchar.h>, but wide characters are not a universal shortcut for processing UTF-8.

Buffer Capacity and Safer Patterns

The central safety rule is that a string destination must have room for every copied character plus its terminating null character. Standard strcpy and strcat do not receive the destination’s capacity, so they cannot check whether a write will fit. The programmer must establish that guarantee before calling them. A fixed-size array is not automatically safe merely because it looks large enough for typical input.

For formatted output, snprintf from <stdio.h> can limit writes to a specified buffer size. Its return value is the number of characters that would have been written, excluding the terminator. When the size is greater than zero, the output is terminated, but it may be truncated; check whether the return value is greater than or equal to the buffer size. A size of zero is permitted for determining the required output length, but no characters are written.

When reading a line into a fixed-size array, fgets accepts the array size and reads at most one fewer character, leaving room for a terminator. It may retain the newline if one fits. The following pattern removes that newline if present:

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

char line[128];
if (fgets(line, sizeof line, stdin) != NULL) {
    line[strcspn(line, "\n")] = '\0';
}

strcspn returns the number of initial characters that contain none of the characters in its second argument. Here it identifies the newline position, or the existing terminator if no newline was read. If the input line is longer than the array, the remainder stays in the input stream; programs that need complete lines must detect and handle that case rather than treating a partial line as complete.

Common Mistakes and How to Avoid Them

  • Forgetting the terminator: A manually filled character array is not a valid string until it has a terminating '\0' within its bounds.
  • Using sizeof on a pointer: Inside a function parameter such as char *s, sizeof s is the size of the pointer, not the size of the pointed-to array. Pass the capacity separately when a function needs it.
  • Assuming strncpy always terminates: It does not when the source length is at least the limit. If using it, arrange termination explicitly and ensure the destination has a byte available.
  • Appending without measuring total space: An append needs room for the existing string, the added text, and one final terminator. An incorrect capacity calculation can write past the array.
  • Modifying a string literal: A pointer initialized from a literal, such as char *p = "hello";, must not be used to modify that text. Use a writable array, for example char p[] = "hello";, when changes are needed.
  • Confusing an empty string with a null pointer: "" is a valid string containing only a terminator. A null pointer points nowhere and is not a string that can safely be passed to strlen or strcmp.

Choosing a Function for the Task

Start by deciding whether the data is text or an arbitrary byte sequence. For text, verify that it is terminated and identify the available capacity. Then select a function according to the operation: use strlen to measure, strcmp to compare, strchr or strstr to search, and a bounded input or formatting routine when writing into a limited buffer. If the data is binary, use memory functions with explicit lengths instead.

There is no single standard function that makes every string operation safe automatically. strlcpy and strlcat exist on some platforms, but they are not ISO C functions, so portable programs cannot assume they are available. Microsoft’s secure CRT functions, such as strcpy_s, are also not universally supported as standard C interfaces. Check the compiler and platform documentation when relying on extensions. In portable code, clear capacity tracking and careful checks are more important than a function name that sounds safe.

Frequently Asked Questions

Which header declares C string functions?

Most standard narrow-character string and memory functions, including strlen, strcmp, and memcpy, are declared in <string.h>. Wide-character string functions such as wcslen are declared in <wchar.h>.

Does strlen include the null terminator?

No. It returns the number of characters before the first '\0'. To allocate an array for a copy of a string, account for one additional byte for the terminator.

Why is strncpy considered tricky?

It may leave the destination unterminated when the source fills the specified limit, and it pads the rest of the destination with null characters when the source is shorter. Those rules can surprise programmers expecting a simple, always-terminated bounded copy.

Can I compare strings with ==?

Not to compare their contents. For ordinary C strings, use strcmp(a, b) == 0. The == operator compares pointer addresses when applied to string pointers.

Are C strings Unicode strings?

A C string is a null-terminated sequence of bytes; the representation is not inherently Unicode. UTF-8 text can be stored in a C string, but many standard string functions count or search bytes rather than Unicode characters or grapheme clusters.

Related

Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.

More in Formulas & functions

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.