C++ String strlen() Function

Beginner
⏱️ 10 min read
📚 Updated: Jul 2026
🎯 5 Examples
C-strings / sizing

What You’ll Learn

The strlen() function answers a basic question: how long is this C-string? It counts characters from the start until (but not including) the null terminator '\0'. Knowing length helps you loop over text, validate input, and size buffers before calling functions like strcpy().

01

Count Chars

Before \0.

02

size_t Return

Unsigned count.

03

Not STL

<cstring> API.

04

+1 Rule

Room for \0.

05

vs size()

std::string length.

06

O(n) Scan

Walk every char.

Definition and Usage

In C++, strlen() is declared in <cstring>. It accepts a pointer to a null-terminated C-string and returns the number of bytes (for plain char text, the number of characters) before the terminating '\0'.

String literals like "Hello, C++!" automatically include a hidden null terminator at the end. strlen sees 11 visible characters and stops—it never counts the twelfth byte that holds '\0'.

💡
Beginner Tip

When allocating memory for a copy with strcpy, allocate strlen(source) + 1 bytes. The extra byte holds the null terminator that strlen does not count.

📝 Syntax

Function signature and a typical call:

C++
#include <cstring>

size_t strlen(const char* str);

// Example:
std::size_t len = strlen("Hello, C++!");
// len == 11

Parameters

  • str — pointer to a null-terminated C-string (literal, char array, or const char*).

Return Value

Returns a size_t equal to the number of characters before the first '\0'. An empty string "" has length 0.

⚡ Quick Reference

Stringstrlen resultNotes
"hi"2Does not count \0
""0Empty string
"Hello, C++!"11Spaces and symbols count
std::string sUse s.size()Not strlen
Length
strlen(str)

Character count

Buffer
strlen(s) + 1

For strcpy

Empty?
strlen(s) == 0

No characters

Include
#include <cstring>

Header file

Examples Gallery

Compile with g++ strlen.cpp -std=c++17 -o strlen. Each example shows a practical way to use or relate to strlen().

📚 Getting Started

Measure a string literal and print the result.

Example 1 — Basic strlen() Usage

Find the length of "Hello, C++!" and display it.

C++
#include <iostream>
#include <cstring>

int main() {
    const char* str = "Hello, C++!";

    std::size_t length = std::strlen(str);

    std::cout << "String: \"" << str << "\"\n";
    std::cout << "Length: " << length << " characters\n";

    return 0;
}

How It Works

strlen counts H e l l o , space C + + ! — eleven characters—then stops at the hidden null terminator stored after the exclamation mark.

Example 2 — Empty String Length

An empty C-string contains only the null terminator, so length is zero.

C++
#include <iostream>
#include <cstring>

int main() {
    const char* empty = "";
    char buffer[1] = { '\0' };

    std::cout << "Literal \"\":  " << std::strlen(empty) << "\n";
    std::cout << "Char array:   " << std::strlen(buffer) << "\n";

    return 0;
}

How It Works

The first byte is already '\0', so the scan ends immediately with count 0. Empty strings are valid and common as initial or default values.

📈 Practical Patterns

Size buffers, compare with std::string, and iterate efficiently.

Example 3 — Size a Buffer for strcpy()

Use strlen + 1 before copying into a dynamically sized array.

C++
#include <iostream>
#include <cstring>

int main() {
    const char* source = "CodeToFun";

    std::size_t chars = std::strlen(source);
    std::size_t bytes = chars + 1; // +1 for '\0'

    char* copy = new char[bytes];
    std::strcpy(copy, source);

    std::cout << "Chars: " << chars << ", bytes allocated: " << bytes << "\n";
    std::cout << "Copy:  " << copy << "\n";

    delete[] copy;
    return 0;
}

How It Works

strlen reports 9 letters; allocation needs 10 bytes so strcpy can store the terminator. In modern C++, prefer std::string to avoid manual new[].

Example 4 — strlen() vs std::string::size()

Compare C-string measurement with the C++ string class.

C++
#include <iostream>
#include <string>
#include <cstring>

int main() {
    const char* cstr = "Tutorial";
    std::string cppStr = "Tutorial";

    std::cout << "strlen:           " << std::strlen(cstr) << "\n";
    std::cout << "std::string size: " << cppStr.size() << "\n";
    std::cout << "Same length?       "
              << std::boolalpha
              << (std::strlen(cstr) == cppStr.size()) << "\n";

    return 0;
}

How It Works

Both report 8 characters for "Tutorial". Use strlen only on null-terminated C-strings; use .size() or .length() on std::string objects.

Example 5 — Loop Using Cached Length

Call strlen once, then iterate—avoid repeated scans in the loop condition.

C++
#include <iostream>
#include <cstring>

int main() {
    const char* word = "strlen";

    std::size_t len = std::strlen(word);

    std::cout << "Characters: ";
    for (std::size_t i = 0; i < len; ++i) {
        std::cout << word[i];
        if (i + 1 < len) {
            std::cout << '.';
        }
    }
    std::cout << "\nTotal: " << len << "\n";

    return 0;
}

How It Works

Storing len once turns an O(n²) pattern (calling strlen every loop test) into O(n). You can also iterate until str[i] != '\0' without calling strlen at all.

🚀 Common Use Cases

  • Buffer allocation — compute strlen + 1 before strcpy or malloc.
  • Input validation — enforce minimum or maximum name lengths.
  • Loop bounds — iterate over each character in a C-string.
  • Formatting output — pad or align text based on length.
  • Interfacing with C APIs — many functions expect you to know string sizes.

🧠 How strlen() Works

1

Start at str[0]

Initialize counter to zero and read the first byte.

Start
2

Check for \0

If current byte is null terminator, stop scanning.

Test
3

Increment and advance

Otherwise add one to counter and move to the next character.

Loop
#

Return count

The counter equals the string length excluding the null byte.

📝 Notes

  • The argument must be a null-terminated C-string—otherwise behavior is undefined.
  • strlen is from the C library (<cstring>), not the C++ STL containers.
  • Do not pass a std::string object directly; use s.c_str() if you must call strlen on its content.
  • Time complexity is O(n) where n is the string length.
  • For binary data that may contain zero bytes, use a length-aware type instead of C-strings.

⚡ Optimization

Cache the result when you need the length more than once. Avoid writing for (i = 0; i < strlen(s); ++i) because strlen rescans from the start on every comparison. Prefer range-for over std::string, or loop until '\0' when working with C-strings in hand-written parsers.

Conclusion

strlen() is the standard way to measure a C-string’s character count. Remember: it excludes '\0', requires a terminated string, and scans linearly. Pair it with the +1 rule whenever you allocate buffers.

Next, learn strncat() to append a bounded number of characters from one C-string to another—a slightly safer cousin of strcat().

💡 Best Practices

✅ Do

  • Ensure strings are null-terminated before calling strlen
  • Use strlen(s) + 1 when sizing copy buffers
  • Cache length in a variable for loops and repeated use
  • Prefer std::string::size() in modern C++ code
  • Include <cstring> and use std::strlen

❌ Don’t

  • Call strlen in a loop condition each iteration
  • Pass char arrays missing a '\0' terminator
  • Assume strlen counts the null byte
  • Use strlen on binary data with embedded zeros
  • Confuse it with sizeof (array size vs text length)

Key Takeaways

Knowledge Unlocked

Five things to remember about strlen()

Use these points whenever you measure C-strings.

5
Core concepts
🔢 02

size_t

Unsigned return.

Return
03

+1 Byte

For terminator.

Buffers
🔄 04

O(n) Scan

Cache result.

Perf
💬 05

std::string

Use .size().

Modern

❓ 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. For example, strlen("hi") returns 2.
size_t strlen(const char* str); Include <cstring>. Pass a pointer to a null-terminated char array or string literal. The return type size_t is an unsigned integer type suitable for sizes and counts.
No. It stops when it reaches '\0' and returns the number of characters before it. To allocate a buffer for strcpy, you need strlen(src) + 1 bytes to hold both the text and the terminator.
strlen() works on C-strings (char arrays ending with '\0') and scans until the terminator. std::string::size() (or length()) returns the character count stored in a string object instantly without scanning. Prefer std::string in modern C++ when possible.
Undefined behavior. strlen() keeps reading memory until it finds a zero byte, which may crash the program or return a nonsense length. Always ensure C-strings are properly terminated.
O(n) in the length of the string because it must walk every character until '\0'. If you need the length repeatedly in a loop, store the result in a variable instead of calling strlen() on every iteration.
Did you know?

sizeof(arr) on a char array gives the total array size in bytes, while strlen(arr) gives the current text length. For char buf[100] = "hi";, sizeof buf is 100 but strlen(buf) is only 2.

Continue the String Functions Series

Measure C-strings with strlen(), then append safely with strncat().

Next: strncat() →

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