strring length in c++
String Length in C++
To find the length of a string in C++, you can use the length()
or size()
member functions of the std::string
class. These functions return the number of characters in the string.
Here's an example:
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, world!";
int length = str.length(); // or str.size()
std::cout << "The length of the string is: " << length << std::endl;
return 0;
}
In this example, the length()
function is called on the str
object to get the length of the string. The result is then printed to the console.
Explanation:
- The std::string
class in C++ provides several member functions to work with strings.
- The length()
and size()
member functions are equivalent and can be used interchangeably to get the length of a string.
- These functions return the number of characters in the string, excluding the null-terminating character.
- The length of the string is stored in an int
variable, which can hold the maximum length of a string in C++.