C String strlen() Function

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

What You’ll Learn

The strlen() function counts how many characters appear in a C-string before the terminating '\0'. It is one of the most frequently used functions in C—essential for allocating buffers, copying strings, and validating input.

01

Count Chars

Not \0.

02

size_t

Return type.

03

Empty = 0

"" length.

04

len + 1

Buffer size.

05

string.h

Standard C.

06

vs sizeof

Array bytes.

Definition and Usage

A C-string is a sequence of bytes ending with a null character. strlen walks from the start until it finds that null byte and returns how many non-null characters it passed.

The count does not include '\0'. When allocating memory for a copy, use strlen(s) + 1 to leave room for the terminator. When checking whether a fixed buffer can hold a string, compare length to available space carefully.

💡
Beginner Tip

Print the result with printf("%zu\n", strlen(s));. The z length modifier matches size_t. Using %d can warn or misprint on some platforms.

📝 Syntax

Standard C declaration:

C
size_t strlen(const char *s);

Parameter

  • s — pointer to a null-terminated C-string.

Return Value

  • Number of characters before '\0', as size_t.
  • 0 for an empty string "".

Header

  • #include <string.h>

⚡ Quick Reference

String sstrlen(s)Bytes needed (with \0)
"Hello, C!"910
""01
"A"12
char buf[32] = "Hi";2sizeof buf is 32
printprintf("%zu", strlen(s));
Length
len = strlen(s);

Char count

Alloc size
strlen(s) + 1

Include \0

Print
printf("%zu", len);

size_t

Array size
sizeof(buf)

Not length

Examples Gallery

Compile with gcc strlen.c -std=c11 -o strlen. Every example includes <string.h>.

📚 Getting Started

Measure the length of a simple string literal.

Example 1 — Basic String Length

Count characters in "Hello, C!".

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

int main(void) {
    const char *message = "Hello, C!";
    size_t length = strlen(message);

    printf("The length of the string is: %zu\n", length);

    return 0;
}

How It Works

The nine visible characters are counted; the hidden '\0' at the end stops the scan but is not included in the result.

Example 2 — Empty String

An empty C-string still has a null terminator, but length zero.

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

int main(void) {
    const char *empty = "";

    printf("Length of empty string: %zu\n", strlen(empty));

    return 0;
}

How It Works

"" points at a null byte immediately, so strlen returns 0 without examining any other characters.

📈 Practical Patterns

Sizing buffers, sizeof pitfalls, and iterating by index.

Example 3 — Size a Buffer for Copying

Use strlen + 1 before allocating or copying.

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

int main(void) {
    const char *name = "CodeToFun";
    size_t chars = strlen(name);
    size_t bytes_needed = chars + 1;

    char dest[16];

    if (bytes_needed <= sizeof dest) {
        strcpy(dest, name);
        printf("Copied %zu chars into buffer of %zu bytes\n",
               chars, sizeof dest);
    }

    return 0;
}

How It Works

Nine characters plus one null byte need ten bytes total. The sixteen-byte array has enough room for strcpy safely.

Example 4 — strlen() vs sizeof()

Array size and string length measure different things.

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

int main(void) {
    char buf[20] = "Hello";

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

    return 0;
}

How It Works

strlen counts five letters before '\0'. sizeof buf is the whole array (20 bytes) fixed at compile time. Never use sizeof on a pointer expecting string length.

Example 5 — Loop Using Length

Print each character using an index from 0 to strlen - 1.

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

int main(void) {
    const char *word = "C-string";
    size_t i, n = strlen(word);

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

    return 0;
}

How It Works

Calling strlen once before the loop avoids recomputing length every iteration. For very hot loops on huge strings, pointer walking can be faster, but strlen once is clear and fine for beginners.

🚀 Common Use Cases

  • Buffer allocationmalloc(strlen(s) + 1) before copy.
  • Bounds checks — verify text fits before strcat or strcpy.
  • Input validation — enforce maximum name or password lengths.
  • Formatting — pad or align output based on text width.
  • Teaching C-strings — connect length to null termination.

🧠 How strlen() Works

1

Start at s[0]

Initialize counter to 0.

Scan
2

Check each byte

If not '\0', increment counter and advance.

Count
3

Stop at \0

Return counter without counting the terminator.

Stop
=

size_t len

Character count excluding null byte.

📝 Notes

  • Requires a null-terminated string—binary blobs need explicit lengths.
  • Time complexity is O(n)—scans the whole string each call.
  • Do not call strlen twice in a row on the same unchanged string in tight loops—cache the result.
  • sizeof(pointer) is pointer size, not string length.
  • Unicode code points are not counted—UTF-8 multibyte sequences count bytes.

⚡ Optimization

Library strlen is highly optimized. If you already know the length (for example from a length-prefixed protocol), store it instead of rescanning. Avoid strlen in inner loops when the string has not changed.

Conclusion

strlen() returns how many characters precede the null terminator. Use %zu to print it, add one for buffer sizing, and never confuse it with sizeof on arrays.

Next, learn strcmp() to compare two strings lexicographically.

💡 Best Practices

✅ Do

  • Print with %zu for size_t
  • Use strlen(s) + 1 when allocating copies
  • Cache length if used multiple times
  • Ensure strings are null-terminated before calling
  • Compare length to buffer capacity before copy

❌ Don’t

  • Use sizeof on a pointer to get string length
  • Assume strlen includes '\0'
  • Call strlen on non-terminated buffers
  • Print size_t with %d habitually
  • Use strlen on binary data without a null byte

Key Takeaways

Knowledge Unlocked

Five things to remember about strlen()

Use these points when working with C-strings.

5
Core concepts
📝 02

size_t

Unsigned.

Type
🔢 03

len + 1

For copy.

Sizing
📈 04

Empty = 0

Still valid.

Edge
💬 05

vs sizeof

Array size.

Compare

❓ Frequently Asked Questions

strlen() counts how many characters appear in a null-terminated C-string before the terminating '\0'. It does not include the null character in the count.
size_t strlen(const char* s); Include <string.h>. The argument must point to a valid null-terminated string.
No. If s is "Hello", strlen returns 5. The null byte marks the end but is not counted.
size_t—an unsigned integer type used for sizes and counts. Print it portably with printf("%zu", len).
strlen() counts characters until '\0' at runtime. sizeof on a char array returns the array size in bytes at compile time, which may be larger than the string length if the array is only partly filled.
Behavior is undefined. strlen keeps reading memory until it finds a zero byte. Always ensure C-strings are properly terminated.
Did you know?

The name strlen stands for string length. It has been part of C since the earliest standard library—every string function you learn (strcpy, strcat, strcmp) assumes you understand that C-strings end with '\0', which is exactly what strlen locates.

Continue the String Functions Series

Measure strings with strlen(), then compare them with strcmp().

Next: strcmp() →

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.

6 people found this page helpful