String Handling Functions in C: A Practical Guide

Formulas & functions · Updated November 22, 2026

C string-handling functions are declared in the standard header <string.h> and work with null-terminated character arrays. The most-used functions measure strings (strlen), copy them (strcpy), join them (strcat), compare them (strcmp), and search them (strchr and strstr); using them safely requires enough destination space and a terminating null character.

How C strings work

C does not have a built-in string type like some other languages. A string is a sequence of characters stored in a char array, followed by the special null character, written '\0'. That final character marks where the text ends; it is not the same thing as the digit character '0'. For example, the text cat occupies four array elements: 'c', 'a', 't', and '\0'.

This representation makes strings compatible with ordinary arrays, but it also means C does not automatically track their length or check array bounds. A string function generally expects its input to contain a null terminator. If it does not, the function may read beyond the array while looking for one, causing undefined behavior. Likewise, a function that writes text needs a destination with enough room for all characters and the terminating null character.

Include <string.h> to use the standard string and byte-manipulation functions. The examples below use standard C functions; a compiler may accept a function without the proper declaration, but relying on that is not portable and can produce incorrect behavior.

Measuring and copying strings

strlen returns the number of characters before the null terminator, not the total size of the array. Its return type is size_t, an unsigned type intended for object sizes. The following example measures the text in an array:

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

int main(void) {
    char word[] = "pear";
    size_t length = strlen(word);
    printf("%zu\n", length);  /* prints 4 */
    return 0;
}

Here, word has room for five characters, including '\0', while strlen(word) is four. Do not call strlen on an unterminated character array or on a null pointer. If you need the capacity of an array in the same scope where it is declared, sizeof word gives its size in bytes; when an array is passed to a function, it is treated as a pointer, so sizeof there does not reveal the original array capacity.

strcpy(destination, source) copies the source string, including its terminator. The destination must have at least strlen(source) + 1 bytes, and the source and destination must not overlap. For a known fixed destination, copying can be appropriate when its capacity is clear:

char source[] = "pear";
char copy[sizeof source];
strcpy(copy, source);

The array copy is large enough because it is sized to match source. In contrast, this would be unsafe if the source could contain more text than the destination can hold. Standard C’s strncpy is not a simple safe replacement: it copies at most the requested number of characters, but if the source fills that limit it may leave the destination without a null terminator. It also pads the destination with null characters when the source is shorter. Use it only when those precise behaviors are wanted and the resulting string is handled correctly.

Joining strings with strcat

strcat(destination, source) appends the source text to the end of the destination string and writes a new terminator. Before calling it, the destination must already be a valid string and must have enough unused capacity for the appended characters plus the terminator. The arrays must not overlap. For example:

char greeting[20] = "Hello, ";
strcat(greeting, "Sam");
/* greeting now contains "Hello, Sam" */

The initial text has seven characters, and Sam has three, so the final string needs eleven bytes including '\0'. The 20-byte array is large enough. A common error is to allocate room for the initial text only, then append without accounting for the additional characters and terminator. strncat limits how many source characters it appends, but its count is not the total destination capacity; callers still have to calculate the available space correctly and ensure termination.

For programs assembling text from variable-length inputs, repeated concatenation can also be inefficient because each call searches the destination for its current end. Keeping an explicit position and remaining capacity, or formatting into a bounded buffer with snprintf from <stdio.h>, can make the sizing logic clearer. snprintf is not declared in <string.h>; it is a formatted-output function.

Comparing strings

Use strcmp(first, second) to compare two null-terminated strings. It returns zero when their contents are equal, a negative value when the first string sorts before the second, and a positive value when it sorts after the second. Do not assume the result will be exactly -1 or 1; test its sign or compare it with zero:

if (strcmp(answer, "yes") == 0) {
    puts("The answer is yes.");
}

This is different from comparing pointers with ==. Pointer equality checks whether two pointers refer to the same address, not whether the strings at those addresses contain the same characters. For example, two separate arrays can both contain "yes" and still have different addresses. strncmp(a, b, count) compares no more than the first count characters, which is useful for a deliberate prefix comparison, but it does not make arbitrary unterminated data safe.

The ordering used by these functions is based on character values, not natural-language rules. It is not automatically case-insensitive, and it does not sort words according to a user’s language. If an application needs locale-aware collation or case folding, it needs additional locale-related facilities and a clearly defined text-encoding policy. For ordinary exact comparisons, strcmp is the standard choice.

Finding characters and substrings

strchr(text, character) searches for the first occurrence of a character and returns a pointer to it, or a null pointer if it is not found. strrchr finds the last occurrence. Both can also find the string’s terminating null character if the search character is '\0'. A returned pointer refers into the original array, so it can be used to inspect or modify that portion of a writable array.

strstr(text, needle) searches for the first occurrence of the substring needle and returns a pointer to its first character, or a null pointer if there is no match. An empty needle matches at the beginning of the text. A practical pattern is to check the result before using it:

char line[] = "status: ready";
char *found = strstr(line, "ready");
if (found != NULL) {
    printf("Match: %s\n", found);
}

These functions search bytes in a C string; they do not understand every human-language notion of a character. In UTF-8 text, a displayed character may consist of multiple bytes, and byte-based searches or positions may not correspond to visible character boundaries. When software must process Unicode text by characters or grapheme clusters, it needs Unicode-aware handling rather than assuming each char is one complete displayed character.

Splitting text with strtok

strtok divides a writable string into tokens separated by any character in a delimiter string. It changes the input by replacing delimiters with null characters. The first call receives the input array; later calls for the same sequence pass NULL as the first argument:

char input[] = "red,green,blue";
char *token = strtok(input, ",");
while (token != NULL) {
    puts(token);
    token = strtok(NULL, ",");
}

This prints the three color names. The delimiter argument is a set of individual delimiter characters, not a multi-character separator treated as one unit. Consecutive delimiters are skipped, so this function does not preserve empty fields in the way some CSV parsers must. Because it modifies the input, do not pass a string literal or read-only storage. Its internal parsing state also makes nested or interleaved tokenization awkward; POSIX systems provide strtok_r, but that function is not part of ISO C. For quoted fields, escaped delimiters, or CSV rules, use a parser designed for that format.

Byte functions in string.h

The header also declares functions for handling raw memory, including memcpy, memmove, memcmp, and memset. Despite sharing <string.h>, these functions operate on a specified number of bytes and do not stop at a null character. That makes them useful for binary data and fixed-size buffers, but different from the null-terminated string functions.

  • memcpy(destination, source, count) copies exactly count bytes; the memory regions must not overlap.
  • memmove(destination, source, count) copies bytes even when the regions overlap.
  • memcmp(first, second, count) compares a fixed number of bytes and returns a sign indicating the ordering of the first difference.
  • memset(destination, value, count) writes the converted byte value repeatedly across the requested number of bytes.

Do not use memset(array, 1, sizeof array) to assign the integer value one to each element of an integer array: it fills each byte with the value one. Similarly, memcmp is not a substitute for strcmp when comparing ordinary strings of different lengths, since it compares the exact byte count supplied and does not stop at terminators.

Choosing functions and avoiding common mistakes

Choose a function according to the operation and its contract, rather than by assuming that a name containing “n” automatically prevents errors. Standard C string functions generally cannot determine the size of the destination array from a pointer. The caller remains responsible for valid pointers, terminated inputs, sufficient capacity, and any overlap restrictions.

  • Measure a valid C string with strlen; use an array’s known capacity separately when writing into it.
  • Copy a complete string with strcpy only when the destination size has been established.
  • Compare contents with strcmp, not pointer equality.
  • Search text with strchr or strstr, and check for a null result before using it.
  • Tokenize only when modifying the input and skipping repeated separators match the required behavior.
  • Use byte functions for counted memory regions, not as interchangeable versions of string functions.

One important misconception is that every value written between double quotes is safe to modify. A string literal such as "hello" has static storage, and attempting to change its contents has undefined behavior. Use a writable array, such as char text[] = "hello";, if modification is needed. If the text should remain unchanged, a pointer to const char, such as const char *text = "hello";, communicates that intent.

Safer alternatives for bounded output

For output assembled from formatted values, snprintf is often useful because it accepts the destination size. It writes no more than the supplied capacity, including room for a terminator when the capacity is greater than zero, and returns the number of characters that would have been produced excluding that terminator. A return value greater than or equal to the capacity indicates truncation. Check the return value when truncation would make the result invalid.

There is no universally available standard C function that takes both destination capacity and source string for every copy or append task. Some platforms provide additional functions such as strlcpy or strlcat, but these are not ISO C functions and are not present in every C environment. Annex K bounds-checking functions are also optional in the C standard and have limited implementation support. Portable code should not assume either family exists unless the target platform or project explicitly guarantees it.

For more complex input, safer design often means tracking a buffer’s capacity and current length explicitly, validating incoming lengths before copying, and reporting an error if text will not fit. Dynamic allocation can accommodate variable-size strings, but allocation size calculations and allocation failures still need checking. No function name by itself removes those responsibilities.

Frequently Asked Questions

Which header file contains C string functions?
Most standard string and byte functions, including strlen, strcpy, strcmp, strchr, and memcpy, are declared in <string.h>. Formatted output functions such as snprintf are declared in <stdio.h>.

Does strlen count the null character?
No. strlen counts characters before the first '\0'. The array’s storage must also include that terminator, so a string with four visible characters normally needs at least five bytes.

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

Is strncpy a safe version of strcpy?
Not automatically. If the source is as long as or longer than the limit, strncpy may not terminate the destination. It also pads short sources with null bytes. Use it only with an understanding of those rules and explicit handling of the destination.

Can string functions handle Unicode?
They can store and search bytes that form encoded text, but the standard functions do not generally interpret Unicode characters or grapheme clusters. In UTF-8, one visible character may use several bytes, so character-level operations need Unicode-aware tools.

Can I use strcat when I do not know the destination size?
No. strcat has no destination-capacity argument and cannot check whether the append fits. Determine available space before writing, use an appropriate bounded formatting approach where suitable, or manage the buffer and its capacity explicitly.

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.