String Functions in C: What They Do and How to Use Them

Formulas & functions · Updated November 22, 2026

String functions in C are library routines, declared in <string.h>, for measuring, copying, joining, comparing, searching and splitting strings. A C string is a sequence of characters ending with a null character, '\0'; because the library functions generally rely on that terminator, callers must provide valid strings and enough space for destination buffers.

What a string means in C

C does not have a built-in string type like some higher-level languages. Text is usually stored in an array of char, or accessed through a pointer to characters. A string’s content ends at the first null character. For example, the array initialized by char word[] = "cat"; contains four bytes: 'c', 'a', 't', and '\0'.

That final byte is essential. An array such as char raw[3] = {'c', 'a', 't'}; holds three characters but is not a null-terminated C string. Passing it to strlen or printf with %s can make the program read beyond the array, causing undefined behavior. A string function cannot infer the array’s size from a pointer.

Include <string.h> to use the standard string declarations. The header provides functions such as strlen, strcpy, strcmp, strchr and strstr. These functions work with null-terminated byte strings; they do not automatically allocate memory or expand a destination array.

Common functions and their jobs

The standard library offers a focused set of operations. Check each function’s contract, especially whether it changes its input and whether it expects a destination buffer.

Function Purpose Important detail
strlen(s) Counts bytes before the terminator Does not include '\0'
strcpy(dst, src) Copies a string Destination must fit the source and terminator
strcat(dst, src) Appends one string to another Destination must have room for both strings and terminator
strcmp(a, b) Compares two strings Returns a negative, zero or positive value
strchr(s, c) Finds the first matching character Returns a pointer or a null pointer
strstr(s, part) Finds the first matching substring An empty search string matches at the start
strtok(s, delimiters) Finds tokens separated by delimiters Modifies the input string

Several functions return pointers into the original array rather than making a new string. A result from strchr or strstr remains valid only while the underlying array remains alive and unchanged in ways that invalidate the pointer. A null pointer means no match was found.

Measuring, copying and joining strings

strlen returns a value of type size_t, an unsigned type intended for object sizes. Use %zu to print it with printf: for a string containing "cat", strlen returns 3, not 4. If you need storage for a copied string, remember that the terminator takes an additional byte.

strcpy(destination, source) copies the source including its terminator, but it does not check the destination capacity. For example, copying "blue" requires at least five bytes. strcat first locates the destination’s existing terminator and then appends the source, so its destination must have enough unused space for the appended text and a new terminator. Both functions also require a destination that can be modified.

For a fixed-size array, check the capacity before copying or appending. One option is to calculate the lengths and use a bounded formatting function such as snprintf, declared in <stdio.h>. For example, with char out[32] and valid strings first and last, snprintf(out, sizeof out, "%s %s", first, last) limits writes to the size of out. Its return value is the number of characters that would have been written, not counting the terminator. A return value greater than or equal to the buffer size signals truncation; a negative return indicates an encoding or output error.

Comparing strings correctly

Use strcmp(a, b) to compare string contents, not the == operator. In C, a == b compares pointer values, meaning whether the pointers refer to the same address; it does not generally compare the characters they point to. strcmp returns zero when the strings match, a negative value when the first differing character in the first string is less, and a positive value when it is greater. The exact nonzero values are not specified, so test the sign rather than expecting precisely -1 or 1.

For example, a condition such as if (strcmp(command, "quit") == 0) checks whether the contents of command equal quit. The ordering is based on character values, not numeric meaning or dictionary rules. Thus, digit strings are not numbers: lexically, "10" sorts before "2". For locale-aware collation, C provides strcoll; for numeric values, convert and validate the input rather than comparing it as text.

Searching within a string

strchr(s, c) searches for the first occurrence of a character, while strrchr(s, c) searches for the last. Both return a pointer to the matching character or a null pointer if it is absent. They can also find the terminating null character when searching for '\0'. Because the search argument is an integer, a character is converted as required by the function’s parameter type.

strstr(text, pattern) finds the first occurrence of a substring and returns a pointer to its first character. It returns a null pointer if the substring is absent; searching for an empty string returns the start of the input. These functions do not create a separate result string. If the program needs an independent copy of a match, it must allocate or provide a destination buffer and copy the required number of bytes safely.

Splitting strings with strtok

strtok is a common way to split a modifiable string into tokens. The delimiter argument is a set of delimiter characters, not a multi-character delimiter sequence. The first call receives the string; later calls pass a null pointer to continue scanning. The function replaces delimiters with null characters, so the original text is changed.

For example, given a writable array containing "red,green,blue", calls using "," as the delimiter return pointers to red, green and blue, followed by a null pointer when no tokens remain. Consecutive delimiters are treated as a run, so this approach does not preserve empty fields. That matters when parsing data such as comma-separated records, where an empty value may have meaning.

strtok also maintains parsing state between calls, which makes nested parsing awkward and can create problems when parsing concurrently. POSIX systems commonly provide strtok_r, a reentrant alternative, but it is not part of ISO C. If preserving the input or empty fields is important, write a small parser that tracks start and end positions, or use a parsing library suited to the data format.

Buffer safety and common mistakes

Many serious C string bugs come from a mismatch between a pointer and the actual capacity of the array behind it. The functions generally receive no capacity argument, so the programmer must establish that the input is terminated and that the destination has enough room.

  • Reserve space for the terminator: copying a string of length n requires at least n + 1 bytes.
  • Do not write to a string literal. A pointer such as char *p = "hello"; points to a string literal that must not be modified. Use an array, such as char p[] = "hello";, when modification is needed.
  • Check return values and lengths before indexing or copying. Avoid computing a buffer size from untrusted input without checking for integer overflow.
  • Do not assume that a bounded function is automatically safe in every use. The caller still needs correct size calculations and valid pointers.
  • Consider overlapping memory separately. strcpy and strcat are not designed for overlapping source and destination regions. For byte-wise overlapping moves, memmove is the standard function intended for that situation.

strncpy is often mistaken for a universally safe replacement for strcpy. It writes at most the specified number of characters, but if the source length is at least that limit, the destination may not end in a null character. When the source is shorter, it pads the remaining destination bytes with zeros, which can be unnecessary work. Use it only when its specific padding and termination behavior is what the program requires.

Strings, byte arrays and international text

String functions operate on bytes, even when a program uses a multibyte encoding such as UTF-8. Consequently, strlen reports bytes before the null byte, not the number of displayed characters. A visible character outside ASCII may occupy multiple bytes. Functions such as strchr can search for a byte, but they do not understand grapheme clusters, Unicode normalization or language-specific case rules.

For raw data that can contain zero bytes, use the memory functions declared in <string.h>, such as memcpy, memmove and memcmp, along with an explicit length. A zero byte ends a C string, so ordinary string functions cannot represent arbitrary binary data correctly. For Unicode-aware operations, use a library designed for the encoding and text operations your application needs; the standard C string routines are intentionally more limited.

Frequently Asked Questions

Which header file contains C string functions?
Most standard C string and memory functions are declared in <string.h>. Include it before calling functions such as strlen, strcmp or strstr. Formatting functions such as snprintf are declared in <stdio.h>.

Is a character array automatically a string?
No. It is a C string only if it contains a null terminator within the accessible array. A character array with no terminator can still hold data, but it must be handled with explicit lengths rather than ordinary string functions.

Why does strcmp return an integer instead of true or false?
Its result communicates ordering as well as equality. Zero means the strings match; a negative or positive result indicates which compares lower. In conditions that only need equality, compare the return value with zero.

Does strlen count the null terminator?
No. It counts the bytes before the first null character. If allocating enough space for a copy, add one byte for that terminator.

What is the safest way to copy a string into a fixed buffer?
Know the buffer capacity, verify that inputs are valid, and use an approach that limits output, such as snprintf with the destination size. Check its return value to detect truncation. No function can make an undersized buffer hold arbitrarily long text without losing data or allocating more space.

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.