String Functions in C: Full Guide with Examples

Formulas & functions · Updated November 23, 2026

String functions in C are library routines declared in <string.h> that operate on null-terminated character arrays, providing copying, concatenation, comparison, searching, and length calculation. The most essential ones are strlen(), strcpy(), strcat(), strcmp(), and strstr(), which every C programmer uses daily.

Why C Strings Need Special Functions

In C, a string is simply an array of char terminated by a null character ('\0'). Unlike higher-level languages, C has no built-in string type or operators for assignment, comparison, or concatenation. The compiler treats "hello" as a 6-element array: h, e, l, l, o, \0. Because arrays cannot be assigned or compared with ==, you need functions that manually loop over the characters. The <string.h> header standardizes these operations, and they are implemented in the C standard library (often highly optimized by the compiler).

Core String Functions and Their Signatures

All functions below require #include <string.h> and assume null-terminated strings unless stated otherwise. Here are the most frequently used ones:

  • size_t strlen(const char *s) – returns the number of characters before the null terminator (excluding the null).
  • char *strcpy(char *dest, const char *src) – copies src into dest, including the null terminator. It does not check buffer size.
  • char *strncpy(char *dest, const char *src, size_t n) – copies at most n characters. If src is shorter, it pads with nulls; if longer, it does not null-terminate dest.
  • char *strcat(char *dest, const char *src) – appends src to the end of dest, overwriting the null terminator.
  • char *strncat(char *dest, const char *src, size_t n) – appends at most n characters and always adds a null terminator.
  • int strcmp(const char *s1, const char *s2) – compares lexicographically; returns negative, zero, or positive if s1 is less than, equal to, or greater than s2.
  • int strncmp(const char *s1, const char *s2, size_t n) – compares at most n characters.
  • char *strchr(const char *s, int c) – returns a pointer to the first occurrence of character c, or NULL.
  • char *strstr(const char *haystack, const char *needle) – returns a pointer to the first occurrence of the substring needle, or NULL.

Safe Versions: strncpy, strncat, and snprintf

The classic functions strcpy and strcat are notorious for buffer overflows because they do not know the size of the destination. The safer variants take a maximum length parameter, but they have quirks:

  • strncpy does not guarantee null termination if the source is longer than n. You must manually set the last character to '\0'.
  • strncat always null-terminates, but it reads the destination’s current length first, which can be inefficient.
  • For formatting strings into a buffer, snprintf(dest, size, "%s", src) is often the safest choice because it always null-terminates and returns the number of characters that would have been written.

Example of safe copying with strncpy:

char dest[10];
strncpy(dest, "Hello, world", sizeof(dest) - 1);
dest[sizeof(dest) - 1] = '\0';

This ensures dest is always null-terminated. In C11, you can use strcpy_s and strcat_s (Annex K) if your compiler supports them, but they are optional and not universally available.

How to Choose the Right Function

Selecting the correct function depends on what you need to do and the safety requirements:

  • Length: Use strlen – it is O(n) and cannot fail on a valid string.
  • Copying: If you control the buffer size, prefer snprintf or strncpy with explicit null termination. Avoid strcpy unless the source is known to fit.
  • Concatenation: Use strncat with the remaining space, or snprintf with "%s%s".
  • Comparison: strcmp for exact equality, strncmp for prefix checks, and strcasecmp (POSIX, not standard C) for case-insensitive comparison.
  • Searching: strchr for a single character, strstr for a substring, and strrchr for the last occurrence of a character.

Common Pitfalls and How to Avoid Them

Even experienced programmers trip over these issues:

  • Off-by-one errors: Remember that strlen does not count the null terminator. Allocate strlen(src) + 1 bytes for a copy.
  • Missing null terminator: After strncpy when source is longer, the destination may not be null-terminated. Always set the last byte.
  • Using strcmp for character comparison: For a single character, use strchr or direct indexing, not strcmp.
  • Modifying string literals: String literals like "hello" are stored in read-only memory on many systems. Passing them to strcpy as the destination will cause a segmentation fault. Always use a writable array.
  • Assuming strlen is constant time: It scans the entire string, so calling it in a loop condition can make your program O(n²). Store the length once.

Performance and Alternatives

Standard library functions are usually optimized with SIMD instructions, so they are faster than hand-written loops. However, for very large strings or repeated operations, consider:

  • memcpy and memmove: For raw byte copying when you know the length, memcpy is faster but does not handle overlapping regions; memmove does.
  • strtok and strsep: For tokenizing, strtok is standard but modifies the input string and is not thread-safe. strtok_r (POSIX) is reentrant.
  • Manual loops: Sometimes you need custom logic (e.g., trimming whitespace) that no standard function provides.
  • Third-party libraries: Libraries like GLib or BSD’s strlcpy and strlcat offer safer alternatives, but they are not standard C.

Frequently Asked Questions

Why does my string print garbage after using strncpy?
Because strncpy does not null-terminate if the source is longer than n. The destination continues past the copied characters. Always manually set the last character to '\0' after calling strncpy.

Can I use == to compare two strings in C?
No. Using == compares the memory addresses of the arrays, not their contents. You must use strcmp or strncmp to compare the actual characters.

What is the difference between strcpy and memcpy?
strcpy copies bytes until it finds a null terminator, and it stops there. memcpy copies an exact number of bytes regardless of content. memcpy is faster for known lengths but does not handle overlapping memory; use memmove for overlap.

Is it safe to use strtok in a multithreaded program?
No, the standard strtok uses a static buffer to remember the position, so it is not thread-safe. Use strtok_r (POSIX) or strtok_s (C11 Annex K) which take a context pointer.

How do I convert a string to an integer?
Use atoi for simple conversion, but it has no error checking. Prefer strtol from <stdlib.h>, which allows you to detect invalid input and set an end pointer.

What happens if I call strlen on a non-null-terminated array?
It will keep scanning memory until it happens to find a zero byte, which can cause a crash or undefined behavior. Always ensure your character arrays are null-terminated before using any string function.

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.