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)– copiessrcintodest, including the null terminator. It does not check buffer size.char *strncpy(char *dest, const char *src, size_t n)– copies at mostncharacters. Ifsrcis shorter, it pads with nulls; if longer, it does not null-terminatedest.char *strcat(char *dest, const char *src)– appendssrcto the end ofdest, overwriting the null terminator.char *strncat(char *dest, const char *src, size_t n)– appends at mostncharacters and always adds a null terminator.int strcmp(const char *s1, const char *s2)– compares lexicographically; returns negative, zero, or positive ifs1is less than, equal to, or greater thans2.int strncmp(const char *s1, const char *s2, size_t n)– compares at mostncharacters.char *strchr(const char *s, int c)– returns a pointer to the first occurrence of characterc, orNULL.char *strstr(const char *haystack, const char *needle)– returns a pointer to the first occurrence of the substringneedle, orNULL.
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:
strncpydoes not guarantee null termination if the source is longer thann. You must manually set the last character to'\0'.strncatalways 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
snprintforstrncpywith explicit null termination. Avoidstrcpyunless the source is known to fit. - Concatenation: Use
strncatwith the remaining space, orsnprintfwith"%s%s". - Comparison:
strcmpfor exact equality,strncmpfor prefix checks, andstrcasecmp(POSIX, not standard C) for case-insensitive comparison. - Searching:
strchrfor a single character,strstrfor a substring, andstrrchrfor 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
strlendoes not count the null terminator. Allocatestrlen(src) + 1bytes for a copy. - Missing null terminator: After
strncpywhen source is longer, the destination may not be null-terminated. Always set the last byte. - Using
strcmpfor character comparison: For a single character, usestrchror direct indexing, notstrcmp. - Modifying string literals: String literals like
"hello"are stored in read-only memory on many systems. Passing them tostrcpyas the destination will cause a segmentation fault. Always use a writable array. - Assuming
strlenis 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,
memcpyis faster but does not handle overlapping regions;memmovedoes. - strtok and strsep: For tokenizing,
strtokis 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
strlcpyandstrlcatoffer 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
- How to Start Data Entry: A Beginner’s Guide
- Google Sheets Percentages: How to Calculate & Format
- Shortcut for Italics? Keyboard & Word Tips
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Python String Operators and Functions ExplainedPython string operators and functions let you manipulate text using built-in operators like + and *, and a…
- Excel MATCH Function: Input Types and Match Modes ExplainedIn Excel, MATCH accepts a lookup value, a one-dimensional lookup array, and an optional match type: 0 requests…
- Excel Sort by Name and Rank: 2 Easy MethodsTo sort by name and then by rank in Excel, use the Sort dialog box (Data > Sort)…
- Excel Custom Number Format: Round Values to ThousandsTo display Excel values rounded to the nearest thousand without changing the stored numbers, apply the custom number…
- Filter Excel Table by Text: Steps, Options, and FixesTo filter an Excel table by text in Microsoft 365 for Windows, select the drop-down arrow in the…
- Excel Convert Text to Dates: Methods, Formulas, and FixesTo convert dates stored as text in Excel, select the cells and use Data > Text to Columns,…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.