char greeting[] = "Hello";C String Functions Reference: Common Operations and Examples
What is C String Functions Reference? Core Concept & Direct Summary
What are the standard string manipulation functions in `<string.h>` (`strlen`, `strcpy`, `strcat`, `strcmp`, `strchr`, `strstr`)?
C has no built-in string type. What it has instead is a convention — a char array ending in a '\0' — plus a library of functions in string.h that operate on those arrays. That library is small, sharp, and used in essentially every C program ever written.
This page is your reference: the functions you'll actually use, what each one does, the syntax, runnable examples, and — importantly — the safety notes that separate code that works in testing from code that works in production. A few of these functions have sharp edges that have caused real security incidents, and knowing which ones is part of being a competent C programmer.
(Suggested image: the hero graphic — a char array showing "H E L L O \0" with a highlighted "null terminator" box, plus a sidebar listing the function names)
How Does C String Functions Reference Work? In-Depth Mechanics & Architecture
The Foundation: What a C String Actually Is
Before the functions make sense, the underlying model has to be clear:
In memory, that's:
Five characters, six slots. The '\0' (null terminator) marks the end. Every string function on this page walks the array looking for that '\0' to know where the string stops — which is exactly why:
- Forgetting the terminator makes functions run off the end into garbage
sizeofgives capacity whilestrlengives content length (from the array-size tutorial)- Buffers must be sized with room for the terminator
You need #include <string.h> for everything below.
Quick Reference Table
Bookmark this one:
(Suggested image: THE key graphic for this page — the table above styled as a clean poster-style reference. This is your most linkable and shareable asset on the page.)
1. strlen() — The Length
Output:
strlen counts characters until the null terminator — not including it. That's the difference from sizeof, which measures the whole array including the terminator.
Performance note worth knowing:strlen walks the whole string every time you call it. In a loop like for (i = 0; i < strlen(s); i++), that turns an O(n) loop into O(n²). Cache it:
A small habit that matters once your strings get long.
2. strcpy() and strncpy() — Copying
strcpy(dest, src) copies the full string including the terminator:
⚠️ strcpy does zero bounds checking. If source is longer than dest, you write straight past the end of the buffer — the classic overflow we first met with gets(). Never use strcpy with untrusted or unpredictable-length input.
strncpy(dest, src, n) limits how much it copies:
Note the trap: strncpy doesn't guarantee a null terminator when the source is longer than n. It copies exactly n characters and stops — leaving dest unterminated unless you add '\0' yourself. This surprises people constantly, because strncpylooks like the safe strcpy but has this quirk.
The relaxed modern approach — snprintf:
snprintf (from stdio.h) always terminates and is genuinely safe. Many modern style guides recommend it over strncpy for exactly this reason.
(Suggested image: side-by-side comparison of strcpy / strncpy / snprintf with the overflow and missing-terminator problems highlighted)
3. strcat() and strncat() — Joining Strings
strcat(dest, src) appends src to the end of dest:
Two requirements: dest must have enough remaining room for both strings plus the terminator, and it must already be a valid string. strcat overwrites the '\0' at the end of dest and starts writing there — no checking.
⚠️ A classic first-time bug:
strcat needs a valid string to append to. Uninitialized, s has no terminator — strcat hunts for one through garbage memory. Initialize first:
strncat(dest, src, n) appends at most n characters and always terminates — a genuinely better behaved function than strncpy:
Use strncat over strcat whenever the input length isn't fully under your control.
4. strcmp() — Comparing
Here's the one that trips up everyone coming from other languages. You cannot compare strings with ==:
The rule: strcmp returns 0 when the strings are equal. That's counterintuitive (you'd expect "true"), but it exists because strcmp is designed for sorting — it returns:
That last line reveals the comparison is character-code based (ASCII), not alphabetical-case-insensitive. 'A' (65) < 'a' (97), so "Apple" sorts before "apple". For case-insensitive comparison you need strcasecmp (POSIX, not standard C) or a manual loop with tolower.
Common forms you'll write:
strncmp(s1, s2, n) compares only the first n characters — useful for prefix checks:
(Suggested image: a "0 means equal?!" callout graphic with a memory diagram showing why == compares addresses rather than characters — this is the #1 string confusion and worth an excellent visual)
5. strchr(), strrchr(), strstr() — Searching
strchr(s, c) finds the first occurrence of a character, returning a pointer to it (or NULL):
Note that found - text — pointer subtraction gives you the index. (That's pointer arithmetic, coming in the pointers cluster — but it's the standard way to convert a search result into a position.)
strrchr(s, c) finds the last occurrence:
This is the standard way to extract a file extension or filename — search from the right.
strstr(s, sub) finds a substring:
Always check for NULL before using the result. Forgetting that check is a reliable way to crash your program, since NULL dereferences are immediate segfaults.
6. strtok() — Splitting Strings
Parsing input inevitably means splitting it into pieces — comma-separated values, space-separated words, path components. strtok does this:
Output:
Three things you must know about strtok:
- The first call takes the string; every subsequent call takes
NULL. That's how it remembers where it left off — it keeps internal state between calls. - It modifies the original string, replacing each delimiter with
'\0'. That's whydatamust be a modifiablechararray, never a string literal (strtok("a,b,c", ",")crashes). - It is not thread-safe and not reentrant — internal static state means two interleaved
strtokloops will corrupt each other. The POSIXstrtok_rvariant takes an explicit state pointer and solves this.
(Suggested image: the strtok state diagram — the string with commas being replaced by '\0' markers, and the "first call passes string, rest pass NULL" rule highlighted)
7. strspn() and strcspn() — Measuring Runs
These two are lesser known but genuinely handy.
strcspn(s, chars) — length of the initial segment before any of the listed characters:
This is the standard way to strip the trailing newline from fgets input — the exact idiom you've seen throughout this series:
strspn(s, chars) — length of the initial segment consisting only of those characters:
Handy for skipping over known prefixes or validating leading characters.
8. Case Conversion — toupper() and tolower()
These live in <ctype.h>, not <string.h>, because they work on single characters:
⚠️ That loop has the strlen performance problem. Better:
The (unsigned char) cast matters more than it looks: passing a negative char value to tolower is undefined behavior. It's a subtle correctness detail that most tutorials skip — good to have in your reference.
Useful ctype.h predicates alongside them: isalpha, isdigit, isspace, isupper, islower, isalnum, and ispunct. Each takes a character and returns non-zero (true) or zero (false).
Putting It Together: A Word Counter
Sample Run:
This one program uses fgets, strcspn, strncpy, strlen, strtok, strchr, tolower, and isdigit — eight functions from the reference, assembled into something genuinely useful. Note the original copy: strtok destroys the string it's given, so if you need the text afterward, keep a copy first. That's a real pattern, not busywork.
Safety Notes: Which Functions to Watch
(Suggested image: a "safe vs risky" color-coded table graphic — this is genuinely useful and pairs well with your earlier gets() safety page)
Common String Function Mistakes
- Comparing with
==— compares addresses, not contents. Usestrcmp(...) == 0. - Expecting
strcmpto return 1 for equal — it returns 0. The<0 / 0 / >0convention is for sorting. - Forgetting to include
<string.h>— implicit declaration warnings and potential runtime chaos. - Copying into an uninitialized or too-small buffer — the overflow family. Always size for content + terminator.
- Forgetting the
'\0'afterstrncpy— the string isn't terminated, and everything downstream misbehaves. - Passing a string literal to
strtok— it modifies the string, and literals are read-only; crash. - Not checking for
NULLfromstrchr/strstr/strtok/fgets— dereferencingNULLis an instant crash. - Using
strlenin a loop condition — O(n²) on long strings. Cache it. - Calling
toupper/tolowerwithout theunsigned charcast — undefined behavior for negative char values. - Assuming
strtokleaves the original intact — it doesn't; delimiters become'\0'permanently.
(Suggested image: "10 String Function Mistakes" checklist graphic — consistent with the series)
Final Thoughts
The C string library is small but sharp. Few functions, straightforward purposes, and a handful of edge cases that matter a great deal: bounds checking, null terminators, strcmp's zero-means-equal convention, and strtok's destructive statefulness.
If you take three things from this page, make them these: always size your buffers for the terminator, always check pointers for NULL, and compare with strcmp, never ==. Those three habits prevent the overwhelming majority of string bugs — and the overflow discipline here is the same discipline that made gets() a cautionary tale.
Next in this cluster: strings as arrays in depth (declaration, initialization, and iteration), then fgets as the safe way to read text, and finally string-to-number conversions.
Runnable C Code Example & Practical Implementation
#include <stdio.h>
#include <string.h>
int main() {
char greeting[32] = "Hello";
char name[] = " World!";
strcat(greeting, name);
printf("Concatenated: %s\
", greeting);
printf("String length: %zu\
", strlen(greeting));
printf("Comparison with 'Hello': %d\
", strcmp(greeting, "Hello"));
return 0;
}Key Takeaways, Best Practices & Memory Safety Rules
strncat, snprintf) and always ensure sufficient buffer capacity for the trailing null byte (+ 1).Frequently Asked Questions & Technical Interview Insights
Technical Interview & Viva Questions
Frequently asked C programming interview questionsQ: What does `strcmp("apple", "banana")` return?
Q: Does `strlen()` include the null terminator `\\0` in its count?
Related Tools, Tutorials & Authoritative References
Recommended Interactive Tools
- Online C Compiler & Runner — Interactive online GCC sandbox to execute C code in real time.
- Online C Code Editor & IDE — Multi-file C programming environment with code formatting.
- C++ Programming Tutorial — Transition from procedural C to Object-Oriented C++ with STL.
- JavaScript Programming Tutorial — Master modern JavaScript fundamentals, DOM APIs, and async patterns.
Authoritative Standards & Citations
- ISO/IEC 9899 (C Language Standard) — Official international C specification by ISO/IEC JTC 1/SC 22/WG 14.
- GNU GCC Documentation — Official reference manual for the GNU Compiler Collection and C libraries.
- The C Programming Language (K&R) — Definitive classic work by Brian Kernighan & Dennis Ritchie at Bell Labs.
- C Reference Documentation (cppreference.com) — Verified reference covering C89 through C23 language features.