C++ <string> - length() Function
The C++ string::length function is used find out the total number of characters in a string. The function returns the number of actual bytes that conform the contents of the string, and it is not necessarily equal to its storage capacity.
Note: Both string::length and string::size functions are synonyms and return the same value.
Syntax
size_t length() const;
size_t length() const noexcept;
Parameters
No parameter is required.
Return Type
Number of characters present in the string.
Time Complexity
Constant i.e, Θ(1)
Example:
In the example below, the string::length function is used find out the total number of characters in the string called str.
#include <iostream> #include <string> using namespace std; int main (){ string str = "Hello World!."; cout<<"The String is: "<<str<<"\n"; cout<<"String length is: "<<str.length()<<"\n"; cout<<"String size is: "<<str.size()<<"\n"; return 0; }
The output of the above code will be:
The String is: Hello World!. String length is: 13 String size is: 13
❮ C++ <string> Library