C string manipulation in standard C is provided mainly by functions declared in <string.h>, including strlen, strcpy, strcat, strcmp, and search functions such as strstr. These functions work with null-terminated byte strings, so choosing the right function also means ensuring that buffers have enough space and that every string ends with a null character.
How C represents strings
C does not have a built-in string type. A string is a sequence of characters stored in an array, with a zero-valued byte, written as '\0', marking its end. For example, the text cat occupies four bytes as a C string: the three letters followed by the terminator. The terminator is not the same thing as the character '0'.
This representation explains both the usefulness and the risks of the standard functions. A function such as strlen looks for the first null byte to find the end; it does not know the array’s capacity. If a string is not terminated, operations that expect a string can read beyond the array, causing undefined behavior. Likewise, a destination must have enough room for the characters and the final null byte when a function copies or appends text.
The declarations are in <string.h>. The header also declares functions that operate on blocks of bytes rather than specifically on strings, such as memcpy and memcmp. Those functions are useful, but their behavior and requirements differ from the null-terminated string functions.
Everyday string functions
These are among the most commonly used functions for measuring, copying, joining, and comparing strings:
strlen(s)returns the number of characters before the first null byte. Its return type issize_t, an unsigned size type. The terminating null byte is not counted.strcpy(destination, source)copies the source string, including its terminator, into the destination. The caller must ensure the destination is large enough.strcat(destination, source)appends the source string to the end of the destination and writes a new terminator. The destination must already contain a valid string and have enough remaining capacity.strcmp(a, b)compares two strings lexicographically. It returns zero if they are equal, a value below zero if the first differing character inais less, or a value above zero if it is greater.
For example, with char name[] = "Mira";, strlen(name) is 4, even though the array needs 5 bytes to hold the text and its terminator. Do not assume strcmp returns exactly -1 or 1; only the sign of a nonzero result is specified. A test such as strcmp(a, b) == 0 is the right way to check equality.
Comparing and searching strings
strncmp(a, b, n) compares no more than the first n characters. It can be useful when a program needs to examine a prefix, but it is not a general substitute for safe input handling. It still expects valid string arguments, and comparison is not necessarily a check that either string has a particular length. For a fixed-length field that may contain arbitrary bytes, use byte-oriented logic instead.
Several functions locate characters or substrings:
strchr(s, c)finds the first occurrence of a character in a string;strrchr(s, c)finds the last. They return a pointer to the match or a null pointer if no match exists.strstr(s, part)finds the first occurrence of a substring. It returns a pointer to its start, or a null pointer when it is absent.strpbrk(s, chars)finds the first character insthat matches any character inchars.strspn(s, chars)counts the initial characters insthat all belong to the setchars;strcspncounts the initial characters that do not belong to that set.
These functions return pointers into the original string, not newly allocated copies. The pointer is useful only while the underlying array remains available and unchanged in a way that invalidates the result. A common pattern is to check for null before using the returned pointer, for example, test whether strstr(text, query) != NULL before treating the substring as found.
Tokenizing and splitting text
strtok divides a string into tokens separated by any character from a delimiter string. For example, the delimiter string ",:;" treats comma, colon, and semicolon as separators. On its first call, pass the string to split; on later calls in the same sequence, pass a null pointer to continue:
char text[] = "red,green;blue";
char *token = strtok(text, " ,;");
while (token != NULL) {
/* Process token here. */
token = strtok(NULL, " ,;");
}
strtok modifies its input by replacing delimiters with null bytes. Therefore, the input must be a writable array, not a string literal, and the original delimiters are not preserved. It also uses internal state between calls, so nested tokenization or interleaved parsing can disrupt a sequence. Its behavior skips runs of delimiters, which means it does not preserve empty fields. For CSV files or formats where quoting, escaping, or empty fields matter, a dedicated parser is usually more appropriate.
Buffer size and bounded operations
Many bugs arise from confusing a limit on the number of characters read with a guarantee that the destination is large enough. The traditional functions strcpy and strcat do not accept a destination size. Before using them, a program must establish that the full result, including its terminator, fits. For a destination of capacity cap, a string of length len needs at least len + 1 bytes.
strncpy(destination, source, n) is often described as a safer strcpy, but that description can mislead. It copies at most n bytes and pads the rest of the destination with null bytes if the source is shorter than n. If the source has at least n characters, the result is not terminated. A caller using it must handle that case explicitly. Similarly, strncat(destination, source, n) appends at most n source characters; n is not the total capacity of the destination. The existing destination length and space for a final null byte still matter.
For formatted copying into a known array, snprintf is often easier to check. It is declared in <stdio.h>, not <string.h>. With char dst[32]; and a valid null-terminated string in src, this pattern detects both formatting errors and truncation:
int result = snprintf(dst, sizeof dst, "%s", src);
if (result < 0) {
/* Formatting error. */
} else if ((size_t)result >= sizeof dst) {
/* Output was truncated. */
}
The return value, when nonnegative, is the number of characters that would have been written, not counting the terminator. The call writes at most the supplied size, including room for a terminator when the size is greater than zero. This example assumes dst is an actual array in the same scope; if it is a pointer, sizeof dst gives the pointer size rather than the allocation capacity. Also avoid overlapping source and destination objects in a formatting call.
Common mistakes and safety issues
String functions do not validate arbitrary input or manage memory automatically. They expect their arguments to satisfy the function’s requirements. Before copying, appending, or searching, consider these common failure points:
- Missing terminator: A character array filled from a file or network may contain no null byte. Do not pass it to a string function until its length and termination have been established.
- Insufficient space: Include the terminator when calculating capacity, and account for any existing text before appending.
- Null pointers: Passing a null pointer where a valid string is required is not a request to process an empty string. Check pointers when they may be null.
- Wrong comparison: Comparing two character pointers with
==compares addresses, not the strings’ contents. Usestrcmpfor content comparison. - Signed character assumptions: When passing a character value to functions such as
tolowerfrom<ctype.h>, convert a possibly signedchartounsigned charfirst, except forEOF. This avoids undefined behavior for negative values.
Buffer overflows can corrupt data, crash a program, or create security vulnerabilities. A length check must be based on the actual destination capacity, not on a guessed maximum input length. When handling text from an external source, validate its encoding and format as well: the standard narrow-character string functions treat bytes as bytes and do not automatically validate UTF-8 or count user-perceived characters.
Strings, byte arrays, and alternatives
Not every array of characters is a C string. A buffer containing a fixed number of bytes may include embedded null bytes or may not have a terminator at all. For such data, use functions designed for explicit byte counts, such as memcpy to copy a known number of bytes and memcmp to compare them. memmove is the byte-copy function to use when source and destination regions may overlap; overlapping regions are not permitted for memcpy.
For line input, fgets reads at most a specified number of characters into a buffer and null-terminates the result when it succeeds. It may leave a newline in the buffer, and a long line may require additional reads. The gets function is not a safe alternative; it was removed from the C standard in C11. POSIX systems commonly provide getline, which can allocate or resize a buffer, but it is not part of ISO C, so portable programs need another approach.
There is no single universally available “safe string” replacement for the standard library. The optional bounds-checking interfaces in Annex K, including names such as strcpy_s, are not implemented by every C library, and their availability should be checked for the target environment. The BSD-origin strlcpy and strlcat functions are also not ISO C functions. For portable code, explicit capacity tracking, careful checks, and functions such as snprintf for formatted output are often practical choices.
If a program needs dynamic strings that grow automatically, a small abstraction built around a pointer, a length, and a capacity can reduce repeated manual bookkeeping. C++ offers the standard std::string type, but it is not a C function or a facility available to C source code. In either language, the right choice depends on whether the program needs fixed buffers, arbitrary byte sequences, or text that changes size frequently.
Frequently Asked Questions
Which header declares C string functions?
Most standard null-terminated string functions, including strlen, strcpy, strcmp, and strstr, are declared in <string.h>. Formatted output functions such as snprintf are declared in <stdio.h>.
How do I compare two strings in C?
Use strcmp(a, b) == 0 to test whether two valid null-terminated strings have equal contents. Do not use a == b unless you specifically intend to compare their addresses.
Is strncpy always safer than strcpy?
No. strncpy can leave the destination unterminated when the source length reaches its limit, and it may pad a large part of the destination. Use it only when its specific behavior is suitable and you handle termination and capacity deliberately.
How do I find a substring in C?
Call strstr(text, pattern). It returns a pointer to the first match or a null pointer if no match exists. Both arguments must be valid null-terminated strings.
Does C have a built-in string type?
No. C represents ordinary strings as character arrays or pointers to characters, with a null byte marking the end. Libraries can provide higher-level string abstractions, but they are not built-in C string types.
Related
- Split a String in Excel: Separate Text into Columns
- Accounting Trial Balance Worksheet: How It Works
- Google Sheets SPLIT Function: How to Separate Text
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Excel Formula for Over Budget? Simple IF CheckThe quickest Excel formula to flag an over-budget item is =IF(B2>C2,"Over","OK"), where B2 holds the actual spend and…
- Excel COUNT Formula Examples: Numbers, Blanks, and TextIn Excel for Microsoft 365, use =COUNT(A2:A20) to count cells containing numbers, including dates and times. For other…
- Excel Formula Checklist v6 AK16: Full GuideThe Excel formula checklist v6 AK16 refers to a specific version (v6) of a community-maintained formula auditing checklist,…
- Power Query Fuzzy Match: How It Works and How to Use ItYes. Power Query can fuzzy-match text when you merge queries, helping connect values that are similar but not…
- Abby Lawson Budget Spreadsheet: Find the Right FileIf you’re looking for an Abby Lawson budget spreadsheet, the name alone does not identify a confirmed official…
- Excel Date Calculation Methods and FormulasIn Excel, calculate dates by adding or subtracting dates and day counts, or use functions such as DATE,…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.