len in cpp
The len
function in C++ does not exist in the standard library. However, you can achieve similar functionality by using the strlen
function from the <cstring>
header. Here is an example of how to use it:
#include <iostream>
#include <cstring>
int main() {
char str[] = "Hello, World!";
int length = strlen(str);
std::cout << "Length of the string: " << length << std::endl;
return 0;
}
In this example, we include the <cstring>
header to access the strlen
function. We declare a character array str
and initialize it with the string "Hello, World!". Then, we use the strlen
function to calculate the length of the string and store it in the variable length
. Finally, we use std::cout
to print the length of the string to the console.
The strlen
function calculates the length of a C-style string by counting the number of characters until it reaches the null character ('\0'
) that marks the end of the string. It does not include the null character in the count.
Note that the strlen
function only works with null-terminated strings, so it is not suitable for calculating the length of a string that does not have a null character at the end.