C Strings

Beginner
12 min read
Updated: Nov 2026
5 examples
<string.h>

Definition and Usage

C has no built-in string type like some languages. In a C tutorial, a string is a char array whose last meaningful character is followed by a null terminator '\0' (byte value 0). Library functions in <string.h> treat that sequence as text.

char arrays vs string literals

Writable text lives in arrays: char greeting[] = "Hello, C!";. Read-only literals use pointers: const char *label = "CodeToFun";. Mutating helpers such as strcpy() and strtok() need a writable buffer—never a literal.

What should beginners learn first?

Include <string.h>, create a char[] buffer, then practice strlen(), strcpy(), strcmp(), and strstr(). Those cover length, copy, compare, and search.

This lesson vs the Functions index

This page is the C strings lesson: null termination, char[] vs literals, buffer safety, and examples. The String Functions index is only a catalog—search and open individual guides such as strlen(). Learn here first, then browse the index.

Leave room for '\0'.

A buffer declared as char word[6] holds at most five visible letters plus the null byte. Overflows are a classic C bug.

Never mutate literals.

Do not pass a string literal to strcpy, strcat, or strtok as the destination. Copy into a char[] first.

Compare with strcmp.

Use strcmp(a, b) == 0 for content equality. The == operator compares pointers, not text.

C Syntax

Create a writable string, include the header, and call library helpers:

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

int main(void) {
    char buffer[] = "Hello, C!";
    const char *label = "CodeToFun";

    printf("buffer length: %zu\n", strlen(buffer));
    printf("label: %s\n", label);

    return 0;
}
/* gcc string_basics.c -std=c11 -o string_basics */

Core C Concepts

Ideas every C strings tutorial builds on:

ConceptExampleNotes
Null terminator'\0'Marks the end of text for strlen and friends
Writable arraychar s[] = "hi";Safe destination for mutating functions
Literal pointerconst char *p = "hi";Read-only; do not write through it
Header#include <string.h>Declares length, copy, compare, and search APIs
Lengthstrlen(s)Counts characters before '\0'
Equalitystrcmp(a, b) == 0Compares content, not pointer addresses

Ways to create strings

FormWritable?Use when
char s[] = "...";YesDefault choice for editable text
char s[32]; then fillYesYou need a fixed buffer for input or copies
const char *p = "...";NoRead-only labels and messages
'A'N/ASingle character—not a string (no '\0')

When to use which function

JobPrefer
Measure lengthstrlen()
Copy / appendstrcpy(), strcat() (or bounded forms)
Test equality / orderstrcmp(), strncmp()
Find textstrchr(), strstr()
Split a linestrtok() on a writable copy

How to Use Strings in C

A practical workflow for this tutorial track:

  1. Add #include <string.h> (and <stdio.h> for printf / fgets).
  2. Declare a char buffer large enough for text plus '\0'.
  3. Initialize with a literal, or fill with strcpy, snprintf, or fgets.
  4. Measure, compare, and search with strlen, strcmp, and strstr.
  5. Only pass writable arrays to mutating functions such as strcat and strtok.
  6. Open the functions index when you need a specific API guide.

Live Preview

Type text to preview strlen(s)—the same idea as calling strlen() after including <string.h>.

C counts characters before '\0'. Spaces and punctuation count; the terminator does not.

Preview
strlen("Hello") = 5

Include tip: #include <string.h>

C Examples

Five starter patterns from a C tutorial. Compile with gcc file.c -std=c11 -o out.

Example 1 — Create and print strings

The smallest working program that stores and displays C text.

C
#include <stdio.h>

int main(void) {
    char language[] = "C";
    const char *site = "CodeToFun";

    printf("Language: %s\n", language);
    printf("Site:     %s\n", site);

    return 0;
}
Functions Index

How It Works

  1. char language[] stores a writable copy of the literal.
  2. const char *site points at a read-only literal.
  3. %s prints characters until '\0'.
  4. The compiler adds the null terminator for string-literal initializers.

Example 2 — char[] vs const char*

Edit an array, then build a combined string in a buffer.

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

int main(void) {
    char editable[] = "Hello";
    const char *readonly = "World";
    char combined[32];

    editable[0] = 'h';  /* OK: array is writable */

    strcpy(combined, editable);
    strcat(combined, ", ");
    strcat(combined, readonly);

    printf("Editable: %s\n", editable);
    printf("Combined: %s\n", combined);

    return 0;
}
strcpy() Tutorial

How It Works

  1. editable[0] can change because the array owns writable memory.
  2. readonly must stay read-only; do not assign through it.
  3. strcpy seeds combined with a valid null-terminated string.
  4. strcat appends only when combined has enough space left.

Example 3 — strlen() and character indexing

Measure length and walk characters by index.

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

int main(void) {
    char word[] = "Hello";
    size_t n = strlen(word);

    printf("Length: %zu\n", n);
    printf("First: %c\n", word[0]);
    printf("Last:  %c\n", word[n - 1]);

    for (size_t i = 0; i < n; i++) {
        printf("word[%zu] = %c\n", i, word[i]);
    }

    return 0;
}
strlen() Tutorial

How It Works

  1. strlen counts bytes before '\0'—five for "Hello".
  2. Valid indices run from 0 to n - 1.
  3. word[n] is the null terminator, not a printable letter.
  4. Cache n if you reuse the length in a loop (strlen is O(n)).

Example 4 — strcpy() and strcmp()

Copy text into a buffer and test whether two strings match.

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

int main(void) {
    const char *input = "yes";
    char buffer[16];

    strcpy(buffer, input);

    if (strcmp(buffer, "yes") == 0) {
        printf("Command accepted.\n");
    } else {
        printf("Unknown command: %s\n", buffer);
    }

    printf("Compare to \"no\": %d\n", strcmp(buffer, "no"));

    return 0;
}
strcmp() Tutorial

How It Works

  1. strcpy copies bytes including the terminating null.
  2. strcmp == 0 means the strings match.
  3. Non-zero means they differ in lexicographic order.
  4. Do not use == to compare string contents in C.

Example 5 — strstr() and strtok()

Search for a substring, then split a CSV-style line into tokens.

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

int main(void) {
    char line[] = "apple,banana,cherry";
    char *found = strstr(line, "banana");

    if (found != NULL) {
        printf("Found at: %s\n", found);
    }

    char *token = strtok(line, ",");
    while (token != NULL) {
        printf("Token: %s\n", token);
        token = strtok(NULL, ",");
    }

    return 0;
}
strtok() Tutorial

How It Works

  1. strstr returns a pointer into the haystack, or NULL.
  2. strtok needs a writable buffer and writes '\0' over delimiters.
  3. First call passes the string; later calls pass NULL.
  4. Copy first if you must keep the original CSV text intact.

Where to Go Next

This page teaches how strings work in C (char[], '\0', buffer safety, examples). The full searchable catalog of every function tutorial lives on the String Functions index—start with these six:

FunctionDescriptionTutorial
strlen()Length excluding the null terminator.Try it
strcpy()Copy source into a buffer.Try it
strcmp()Compare two strings.Try it
strstr()Find a substring.Try it
strcat()Append text to a buffer.Try it
strtok()Split on delimiter characters.Try it

Need memcpy, strchr, strspn, case helpers, or the rest? Open the complete String Functions index.

Edge Cases & Pitfalls

Most C string bugs come from missing null terminators, tiny buffers, or writing into literals.

\0

Missing null terminator

After manual edits, always write '\0'. Otherwise strlen and printf("%s") read past the buffer.

buf

Buffer too small for strcpy/strcat

Destination must fit existing text + new bytes + '\0'. Prefer bounded copies when size is known.

lit

Writing into a string literal

char *p = "hi"; p[0] = 'H'; is undefined behavior. Use char p[] = "hi"; instead.

==

Comparing with ==

a == b compares pointers. Use strcmp(a, b) == 0 for content.

tok

strtok destroys the buffer

strtok inserts nulls over delimiters and is not thread-safe. Copy first if you need the original line.

n

strncpy may omit '\0'

If the limit cuts the copy short, manually terminate: dest[sizeof(dest) - 1] = '\0';.

Platform Support

<string.h> is part of standard C. A few helpers in this series are compiler or POSIX extensions.

API familySupportNotes
ISO C (strlen, strcpy, strcmp, …)FullPortable across GCC, Clang, and MSVC
POSIX (strcasecmp, strdup)Common on UnixMay need feature-test macros; not ISO C
Windows / MSVC (stricmp, _strlwr)MSVC familyNames often differ; tutorials note portable alternatives
Extensions (strrev, strset)VariesUseful historically; prefer portable loops in new code

Core functions such as strlen, strcpy, strcmp, strstr, and strtok are portable C89/C99/C11 APIs. When an extension appears in the index, the tutorial calls that out and shows a portable pattern.

Key Takeaways

  • C strings are null-terminated char arrays—not a separate language type.
  • Start with strlen, strcpy, strcmp, and strstr.
  • Use writable arrays for mutating calls; keep literals read-only.

One line: C strings are char[] + '\0'—size buffers carefully, compare with strcmp, then open the functions index for details.

Frequently Asked Questions

A C string is a null-terminated array of char values—a sequence of characters ending with '\0'. You store text in char arrays like char name[50] = "Mari"; or point at string literals with const char*. The standard library in string.h provides functions to measure, copy, compare, and search strings.
char buffer[] is an array you can modify (writable memory). const char* points at read-only literal text or any char sequence. Never pass a string literal to functions that write into the string, such as strcpy or strtok—use a char array copy instead.
It marks the end of the string. Functions like strlen stop counting at the first '\0'. Forgetting to null-terminate after manual edits causes strlen and strcpy to read past your buffer—undefined behavior.
Use strcat(dest, src) to append when dest has enough space, or snprintf(dest, sizeof(dest), "%s %s", a, b) for safer formatting. strcat requires dest to already contain a valid null-terminated string.
Some do, some do not. strcpy, strcat, and strtok modify buffers. strlen, strcmp, strchr, and strstr only read. Always check each function's tutorial and never mutate string literals.
Learn char arrays and null termination on this page, then open the String Functions index for strlen(), strcpy(), strcmp(), strchr(), and strstr(). Those five functions cover length, copy, compare, and search—the core of C text handling.

Explore every string function

Open the function index for searchable guides with syntax, examples, and FAQs.

String Functions 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.

8 people found this page helpful