What is std::basic_string::capacity in C/C++?
The class template basic_string provides many functional operations on strings, such as searching, sorting, copying, clearing, etc. std::basic_string::capacity() is a member function of the basic_string class that gets the capacity of a given string.
What does std::basic_string::capacity() do?
std::basic_string::capacity() returns the number of characters that a string can store, meaning it returns the storage capacity of strings. The exact capacity of a string depends on the implementation.
The capacity can be greater than or equal to the string’s length.
Header
This function requires the following header file:
#include <string>
Syntax
string.capacity();
Code
#include <iostream>#include <string>using namespace std;void print(string str){cout<<str<<endl;cout<<"The length of string is:"<<str.length()<<endl;cout<<"The capacity of string is:"<<str.capacity()<<endl;}int main() {string str("Happy Learning");print(str);string empty("");print(empty);//increase length of strstr+=" at educative";print(str);return 0;}
Max size
The maximum size is another property associated with strings. The maximum size dictates the largest possible size a string can have, and if the value is exceeded, the compiler throws a length error exception. The max size depends on the operating system and architecture design.
#include <iostream>#include <string>using namespace std;int main() {string str("Edpresso");cout<<str.max_size()<<endl;cout<<str.capacity()<<endl;cout<<str.length()<<endl;return 0;}