Finding String Length in C++
You can determine the length of a string (number of characters) using the length()
or size()
member functions.
Example: Using length()
Function
#include <iostream>
#include <string>
int main() {
std::string txt = "Hello, World!";
std::cout << "Length of string: " << txt.length() << std::endl;
return 0;
}
Output:
Length of string: 13
Key Takeaways
length()
andsize()
functions return the number of characters in a string.- Useful for iterating over strings or validating input.
- Both functions are interchangeable for
std::string
objects.