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

Formulas & functions · Updated November 22, 2026

C string functions are library routines for measuring, copying, joining, comparing, searching, and splitting null-terminated character sequences; most are declared in the standard header <string.h>. They work on bytes rather than on a dedicated string type, so using them safely depends on providing valid null-terminated data and enough space in destination arrays.

What C Means by a String

C does not have a built-in string type like some other languages. A C string is a sequence of characters stored in a char array or accessible through a pointer, followed by a special zero-valued character called the null terminator, written as \0. The terminator marks where the string ends; it is not the same as the digit character '0'.

For example, char word[] = "cat"; creates an array containing the bytes for c, a, and t, followed by \0. The array therefore needs room for four characters, even though the visible word has only three. The compiler adds the terminator when initializing an array from a string literal.

String functions generally find the end by scanning until they encounter that terminator. If a character array has no terminator within its valid storage, passing it to a function that expects a string can make the function read beyond the array. That can cause incorrect results, crashes, or security vulnerabilities.

The Header and the Main Function Groups

Include <string.h> to use the standard C string and byte-manipulation functions. The header declares functions; it does not create a string object or automatically check whether your buffers are large enough. A typical program also includes <stdio.h> if it uses input or output routines such as printf.

The most frequently used standard functions fall into several groups:

  • Length: strlen counts bytes before the terminator.
  • Copying and joining: strcpy, strncpy, strcat, and strncat.
  • Comparison: strcmp and strncmp.
  • Searching: strchr, strrchr, and strstr.
  • Tokenizing: strtok.
  • Byte operations: memcpy, memmove, memcmp, and memset.

These functions have different requirements. In particular, the mem functions operate on a specified number of bytes and do not stop at a null terminator. They are useful for raw data as well as text, but they are not interchangeable with string operations.

Measuring, Copying, and Joining Strings

strlen(s) returns the number of bytes before the first null terminator. It does not count the terminator or report the size of the array holding the string. For "cat", its result is 3. Because it scans the string, it takes time proportional to the string’s length; calling it repeatedly in a loop can repeat that scan.

strcpy(destination, source) copies the source string, including its terminating null character. The destination must have room for every copied byte, including the terminator. strcat(destination, source) finds the end of the existing destination string and appends the source, again including the final terminator. The destination must have room for its original contents, the added contents, and the terminator.

For instance, with char text[32] = "red";, strcat(text, " fox"); produces "red fox". The array has sufficient capacity for this example. In contrast, an array declared as char text[4] = "red"; has no free space for the appended text, so using strcat on it would write outside the array.

strncpy and strncat accept a limit, but that limit does not make them automatically safe. strncpy copies at most the specified number of bytes and may leave the destination without a terminator when the source is that long or longer. If it copies a shorter source, it pads the remaining limit with null bytes. strncat appends at most the specified number of source bytes and then writes a terminator; its limit is not the total destination capacity. The caller must still calculate available space correctly.

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 bytes. The result is negative when the first string sorts before the second, zero when the compared strings match, and positive when the first sorts after the second. The exact positive or negative value is not specified, so test its sign rather than expecting a particular number.

A common error is to compare strings with ==. For character pointers, that checks whether the pointers refer to the same location, not whether the text is equal. For example, strcmp(name, "Mira") == 0 tests whether the contents match. String comparison is case-sensitive and follows the character values used by the implementation; it is not a general language-aware alphabetical comparison.

strncmp can be useful for checking a prefix, but only when the input is a valid string or otherwise has enough accessible bytes for the operation. It also does not mean “compare safely up to the destination buffer size” in every context; the caller still needs to understand the memory available at both pointers.

Searching and Tokenizing

strchr(s, c) searches for the first occurrence of a character in a string, while strrchr(s, c) finds its last occurrence. Both return a pointer to the matching character, or a null pointer if it is not found. They can also find the string’s terminating null character when searching for '\0'. strstr(s, part) searches for the first occurrence of a substring and returns a pointer to its start, or a null pointer when there is no match.

These return values point into the original string; they do not make a copy. A program can use the pointer to inspect or modify that part of a writable array, but must not modify a string literal. For example, char *dot = strrchr(path, '.'); can locate the last period in a path-like string. Check that dot is not null before using it as a match.

strtok splits a writable string into tokens separated by any character in a delimiter string. It changes the input by replacing delimiters with null characters and keeps parsing state between calls. A typical pattern is to call it once with the input, then repeatedly with a null pointer until it returns null. Because it modifies its input and uses internal state, it is unsuitable when the original text must remain intact or when parsing calls need independent state. Some systems provide strtok_r or strtok_s, but those are not part of the portable ISO C string-function set.

Boundaries, Safety, and Common Mistakes

The main safety question for a copying or joining operation is: how many bytes are actually available in the destination? C string functions do not know an array’s capacity from a pointer, and the classic functions do not receive a destination-size argument. A limit parameter helps only if it is derived from the true remaining capacity and the function’s specific rules are understood.

  • Reserve one byte for \0 whenever you build a string in an array.
  • Do not use strlen on data unless a terminator is known to occur within the accessible object.
  • Do not pass overlapping source and destination regions to strcpy, strcat, or their bounded variants; their behavior is not defined for overlapping copies.
  • Check return values from searches and other functions that can report failure with a null pointer.
  • Remember that sizeof(array) gives an array’s storage size only where the expression still refers to the actual array. A function parameter declared as an array is adjusted to a pointer, so sizeof there gives the pointer size instead.

For overlapping byte regions, memmove is designed to handle overlap, unlike memcpy. It still takes a byte count rather than enforcing string rules, so after moving characters you may need to place a terminator yourself. Also, strncpy is not a universal secure replacement for strcpy: its padding behavior and possible missing terminator can produce bugs of their own.

Bytes, Character Encodings, and Alternatives

The standard string functions are byte-oriented. With UTF-8 text, a displayed character can use multiple bytes, so strlen reports the number of encoded bytes, not necessarily the number of visible characters. Similarly, stepping one byte at a time through a UTF-8 string can land in the middle of a multibyte character. Code that needs user-perceived character counts, normalization, or language-sensitive comparison needs Unicode-aware facilities beyond the basic <string.h> functions.

For formatted construction, snprintf from <stdio.h> is often a useful alternative because it receives the destination buffer size and writes no more than that many bytes, including room for a terminator when the size is nonzero. Its return value can be checked to determine whether the output was truncated. It is a formatted-output function, not a member of the <string.h> family, and the format string must still match the supplied arguments.

Some platforms offer functions such as strlcpy or strlcat, and some C implementations provide optional bounds-checking interfaces such as the Annex K functions. These are not universally available as portable ISO C functions. When writing code intended to compile across implementations, check the target library’s documentation or use standard facilities with explicit capacity calculations.

Choosing the Right Function

Choose by the operation and the representation of the data, not simply by which function name looks safest. For text known to be a valid C string, use strlen to measure, strcmp to compare, and the search functions to locate characters or substrings. For raw buffers with known byte lengths, use the appropriate mem function rather than treating the data as a string.

For copying into a fixed-size array, first determine the destination capacity and the maximum content length that leaves space for the terminator. If truncation is acceptable, implement and document that behavior explicitly, and ensure the result is terminated. If truncation is not acceptable, detect insufficient space and report or handle the error instead of silently producing partial text. Clear ownership of buffers and explicit lengths make these decisions easier to review.

For example, a program reading a line into a fixed-size array should distinguish a complete line from input that exceeded the available space. Simply calling a string-copy routine after reading does not recover text that was already truncated, and comparing the resulting prefix may mistakenly treat different longer inputs as equal. Validate lengths at the point where data enters the program.

Frequently Asked Questions

What header file declares C string functions?
Most standard C string and byte functions, including strlen, strcmp, strcpy, and memcpy, are declared in <string.h>. Functions such as snprintf are declared in <stdio.h>.

Does strlen count the null terminator?
No. strlen counts the bytes before the first \0. The storage required for a string must include an additional byte for that terminator.

Why should I use strcmp instead of ==?
For character pointers, == compares pointer addresses. strcmp compares the character sequences and returns zero when the strings are equal.

Is strncpy safer than strcpy?
Not automatically. It limits how many bytes it copies, but it may not terminate the destination if the source fills the limit, and it may pad the destination. Safe use requires correct capacity calculations and an explicit plan for termination and truncation.

Are C string functions Unicode-aware?
No. The standard functions in <string.h> operate on bytes. UTF-8 characters may span several bytes, so byte counts and byte-wise operations do not necessarily correspond to visible characters.

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.