In C++, a string is a sequence of characters stored in a contiguous block of memory.
To find the length of a string, we can use the size() or length() function.
Here’s a simple C++ program that demonstrates how to find the length of a string:
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
std::cout << "The length of the string is: " << str.length() << std::endl;
return 0;
}
In this program, we first include the iostream and string header files to use the required functions. Then, we define a string variable str and initialize it with the value “Hello, World!”.
Next, we use the length() function to find the length of the string, which is then printed to the console using cout.
Finally, the main() function returns 0 to indicate successful completion.
Note that the size() function is equivalent to length() and can be used interchangeably to find the length of a string.
That’s it! With just a few lines of code, we can easily find the length of a string in C++.




