How to use strlen to find the length of a string in C++?

In C++, you can use the strlen function to find the length of a string. The strlen function takes a pointer to a null-terminated string as a parameter and returns the length of the string (excluding the null terminator).

Here is an example code:

#include <iostream>
#include <cstring>

int main() {
    const char *str = "Hello, World!";
    int length = strlen(str);
    
    std::cout << "Length of the string: " << length << std::endl;
    
    return 0;
}

In the above example, a pointer str pointing to the string “Hello, World!” is first defined. Then the strlen function is used to find the length of the string, and the result is stored in the variable length. Finally, the length of the string is printed.

bannerAds