how to find length of character array in c++
To find the length of a character array in C++, you can use the strlen
function from the C standard library. Here are the steps to do it:
- Include the
<cstring>
header file at the beginning of your code to access thestrlen
function. - Declare a character array and assign it a value.
- Use the
strlen
function to find the length of the character array. - Store the result in a variable.
- Print the length of the character array.
Here is an example that demonstrates these steps:
#include <iostream>
#include <cstring>
int main() {
char arr[] = "Hello, World!"; // Step 2
int length = strlen(arr); // Step 3
std::cout << "Length of the character array: " << length << std::endl; // Step 5
return 0;
}
In this example, the character array arr
is assigned the value "Hello, World!"
. The strlen
function is then used to find the length of arr
, and the result is stored in the variable length
. Finally, the length is printed to the console using std::cout
.
The output of this example will be:
Length of the character array: 13
This indicates that the character array arr
has a length of 13 characters, including the null terminator.