C Standard Library string.h

Beginner
⏱️ 14 min read
📚 Updated: Jul 2026
🎯 5 Examples
<string.h>

What You’ll Learn

C has no built-in string type—text is a char array ending with '\0'. <string.h> supplies the standard toolkit: copy (strcpy), join (strcat), measure (strlen), compare (strcmp), and search (strstr). Master these and you can parse input, build messages, and work with files alongside <stdio.h>.

01

strlen

Length.

02

strcpy

Copy.

03

strcat

Append.

04

strcmp

Compare.

05

strstr

Find text.

06

\0

Terminator.

Definition and Usage

A C string is a sequence of characters stored in consecutive memory, terminated by a null character '\0' (byte value 0). Functions in string.h assume this layout—they read until they see '\0' unless a length limit applies (strncpy, strncat, strncmp).

The header also defines memory helpers—memcpy, memmove, memset, memcmp—that work on raw bytes, not necessarily null-terminated strings.

💡
Beginner Tip

Before strcpy or strcat, know the destination buffer size. A classic bug is char buf[5]; strcpy(buf, "hello!");—six characters plus '\0' do not fit. Use strncpy with manual null termination, or snprintf from <stdio.h>.

📝 Syntax

Include the header:

C
#include <string.h>

Common string functions

  • strlen(s) — length of string (excludes '\0')
  • strcpy(dest, src) — copy src into dest
  • strncpy(dest, src, n) — copy at most n characters
  • strcat(dest, src) — append src to end of dest
  • strncat(dest, src, n) — append at most n characters
  • strcmp(a, b) — lexicographic compare; 0 if equal
  • strncmp(a, b, n) — compare at most n characters
  • strchr(s, c) — find first occurrence of character c
  • strstr(haystack, needle) — find first substring

Memory functions (also in string.h)

  • memcpy(dest, src, n) — copy n bytes (non-overlapping)
  • memmove(dest, src, n) — copy n bytes (overlapping OK)
  • memset(dest, value, n) — fill n bytes with value
  • memcmp(a, b, n) — compare n bytes

Typical patterns

C
size_t len = strlen(msg);

strncpy(dest, src, sizeof(dest) - 1);
dest[sizeof(dest) - 1] = '\0';

if (strcmp(a, b) == 0) { /* equal */ }

char *p = strstr(text, "error");
if (p != NULL) { /* found */ }

Headers and linking

  • #include <string.h> — uses size_t from <stddef.h>.
  • Linked automatically; no extra flags.
  • See also C string function tutorials for per-function deep dives.

⚡ Quick Reference

FunctionActionReturns
strlenCount characterssize_t length
strcpyCopy stringdest
strcatAppend stringdest
strcmpCompare strings<0, 0, or >0
strchrFind characterPointer or NULL
strstrFind substringPointer or NULL
Length
strlen("hi") /* 2 */

No \0 counted

Equal?
strcmp(a,b)==0

Not a==b

Safe n
strncpy(d,s,n)

Then \0

Find
strstr(s,"key")

Substring

Examples Gallery

Compile with gcc file.c -std=c11 -o out. Buffers are sized generously so strcpy/strcat are safe in these demos.

📚 Getting Started

Core string operations from the reference.

Example 1 — strcpy, strcat, strlen, strcmp

From the reference: copy, concatenate, measure, and compare strings.

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

int main(void) {
    char str1[32] = "Hello, ";
    char str2[] = "World!";
    char str3[32];

    strcpy(str3, str2);
    printf("str3: %s\n", str3);

    strcat(str1, str2);
    printf("str1: %s\n", str1);
    printf("Length of str1: %zu\n", strlen(str1));

    printf("strcmp(str2, str3): %d\n", strcmp(str2, str3));

    return 0;
}

How It Works

str1 must hold "Hello, " + "World!" + '\0' (13 + 1 bytes). strcmp returns 0 when strings match. The old reference output omitted the str3 line—both copies of "World!" compare equal.

Example 2 — strncpy with Manual Null Terminator

Copy only part of a string safely into a fixed buffer.

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

int main(void) {
    char dest[20];
    char source[] = "Hello, World!";

    strncpy(dest, source, 5);
    dest[5] = '\0';

    printf("First 5 chars: \"%s\"\n", dest);
    printf("Full source length: %zu\n", strlen(source));

    return 0;
}

How It Works

strncpy(dest, source, 5) copies "Hello" but does not add '\0' if the limit is reached mid-string—you must set dest[5] = '\0'. Safer pattern: strncpy(dest, src, sizeof(dest)-1); dest[sizeof(dest)-1]='\0';

📈 Practical Patterns

Comparison, search, and raw memory.

Example 3 — strcmp and strncmp

Sort order and prefix matching from the reference.

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

int main(void) {
    char a[] = "Hello";
    char b[] = "World";
    char c[] = "Help";

    printf("strcmp(\"Hello\", \"World\"): %d\n", strcmp(a, b));
    printf("strncmp(\"Hello\", \"Help\", 3): %d\n", strncmp(a, c, 3));

    if (strcmp(a, b) < 0) {
        printf("\"Hello\" comes before \"World\"\n");
    }

    return 0;
}

How It Works

strncmp(a, c, 3) compares only "Hel" vs "Hel"—result 0. Never use == to compare string contents; compare pointers addresses. Use strcmp or strncmp.

Example 5 — memset (Clear a Buffer)

Zero memory before use—common with buffers from malloc.

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

int main(void) {
    char buf[16];

    memset(buf, 0, sizeof(buf));
    strcpy(buf, "Ada");

    printf("buf = \"%s\" (len %zu)\n", buf, strlen(buf));

    memset(buf, '-', 5);
    buf[5] = '\0';
    printf("buf = \"%s\"\n", buf);

    return 0;
}

How It Works

memset sets every byte—not the same as assigning a string. Use memset(buf, 0, n) to clear buffers. For copying overlapping regions, use memmove instead of memcpy.

🚀 Common Use Cases

  • User input — trim, compare commands with strcmp.
  • Building pathsstrcat directory + filename (with size checks).
  • Parsing logsstrstr to find keywords like "ERROR".
  • Sorting names — pass strcmp to qsort from <stdlib.h>.
  • Tokenizing — combine strchr with loops (or strtok carefully).
  • Binary datamemcpy/memcmp for structs and buffers.

🧠 How C Strings Work with string.h

1

Char array + \0

Text lives in memory as bytes ending with null.

Layout
2

Functions scan bytes

strlen counts until '\0'; strcpy copies until '\0'.

Algorithm
3

You manage size

C does not track capacity—overflow is your responsibility.

Safety
=

Portable text ops

Same function names on every platform that supports standard C.

📝 Notes

  • String literals are read-only—do not strcpy into them.
  • strncpy may pad with zeros if source is shorter than n—surprising but standard.
  • strtok modifies the string and is not re-entrant—avoid in threaded code.
  • Do not pass overlapping buffers to strcpy/strcat—use memmove.
  • strlen is O(n)—cache length if you need it repeatedly in a loop.
  • Comparing with == checks pointer equality, not string content.

⚡ Optimization

Standard library string functions are highly tuned. Avoid hand-rolled loops unless profiling proves a bottleneck. Reduce repeated strlen calls, prefer single-pass parsing, and use memcmp for fixed-length binary keys. For many small strings, consider storing length alongside data (common in custom string types).

Conclusion

<string.h> is essential for text in C. Start with strlen, strcpy, strcat, and strcmp, then add strncpy, strstr, and memory helpers. Always respect buffer sizes and the null terminator.

For deeper coverage of each function, explore the C string functions tutorial series.

💡 Best Practices

✅ Do

  • Size buffers for content + '\0'
  • Null-terminate after strncpy
  • Use strcmp for content comparison
  • Check strstr/strchr for NULL
  • Prefer snprintf to build strings when possible
  • Use memmove for overlapping copies

❌ Don’t

  • strcpy into a too-small buffer
  • Compare strings with ==
  • Forget '\0' after partial copies
  • Assume strncpy always null-terminates
  • Modify string literals
  • Use strcat without checking remaining space

Key Takeaways

Knowledge Unlocked

Five things to remember about string.h

Strings in C, explained simply.

5
Core concepts
📚 02

strlen

Count chars.

Measure
📈 03

strcmp

Not ==.

Compare
📄 04

strncpy

Bounded.

Safe
🌐 05

strstr

Find sub.

Search

❓ Frequently Asked Questions

string.h is the C standard header for manipulating null-terminated character arrays and raw memory blocks. It provides strcpy, strcat, strlen, strcmp, strncpy, strchr, strstr, memcpy, memset, and related functions used in almost every C program that handles text.
strcpy copies until it hits the source null terminator—if the destination is too small, you get a buffer overflow. strncpy copies at most n bytes but may not add a null terminator if the source is longer than n. After strncpy, set destination[n-1] = '\0' or use snprintf for safer copies.
strcmp compares two strings lexicographically. It returns 0 if they are equal, a negative value if the first string sorts before the second, and a positive value if the first sorts after. Do not assume the values are exactly -1 or 1—only check < 0, == 0, or > 0.
No. strlen returns the number of characters before the terminating '\0'. A string "hi" has length 2. The array must be big enough to hold the characters plus the null byte—"hi" needs at least char buf[3].
strcat appends to the end of the destination string without checking remaining space. You must ensure the destination buffer has room for the existing text, the new text, and the final '\0'. Prefer strncat with a size limit or snprintf to build strings safely.
strchr finds the first occurrence of a single character in a string. strstr finds the first occurrence of a whole substring. Both return a pointer to the match or NULL if not found.
Did you know?

The name string.h is historical—the header also defines memory routines like memcpy that work on any bytes, not only null-terminated text. That is why binary code includes string.h even when no “strings” are involved.

Explore C Standard Library Headers

Continue with time.h or browse string function tutorials.

Standard Library Index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful