strlen() function in C++

In this guide, you will learn what is strlen() function is in C++ programming and how to use it with an example.

1. strlen() Function Overview

The strlen() function in C++ is used to find the length of a given string. It returns the number of characters in the string, excluding the null terminator. The function belongs to the <cstring> header.

Signature:

size_t strlen(const char* str);

Parameters:

- str: A pointer to the string whose length is to be determined.

2. Source Code Example

#include <iostream>
#include <cstring>

int main() {
    char greeting[] = "Hello, C++!";

    // Finding the length of the greeting string using strlen
    size_t length = strlen(greeting);

    std::cout << "Length of the string '" << greeting << "' is: " << length;
    return 0;
}

Output:

Length of the string 'Hello, C++!' is: 11

3. Explanation

1. The required header files, <iostream> for input/output operations and <cstring> for strlen(), are included.

2. A character array named greeting is initialized with the string "Hello, C++!".

3. The strlen() function is called to determine the length of the greeting string.

4. The computed length is printed using the std::cout statement.

The strlen() function provides a straightforward way to calculate the length of a string without counting the null terminator.


Comments