C++ Standard Library C++ STL Library

C++ <string> - capacity() Function



The C++ string::capacity function returns size of currently allocated space to the string, expressed in terms of characters. The returned value is not necessarily equal to the string length. It can be greater than or equal to as compared to the string length, with the extra space required for the string object to optimize its operations.

Syntax

size_type capacity() const;
size_type capacity() const noexcept;

Parameters

No parameter is required.

Return Type

Returns size of currently allocated space to the string, measured in terms of number of characters it can hold.

Example:

In the example below, the string::capacity function is used find out the size of currently allocated space to the string MyString.

#include <iostream>
#include <string>

using namespace std;
 
int main (){
    string MyString = "Hello World!.";

    cout<<"The String is: "<<MyString<<"\n";
    cout<<"String length: "<<MyString.length()<<"\n";
    cout<<"String size: "<<MyString.size()<<"\n";
    cout<<"String capacity: "<<MyString.capacity()<<"\n"; 
    return 0;
}

A possible output could be:


The output of the above code will be:

The String is: Hello World!.
String length: 13
String size: 13
String capacity: 15

❮ C++ <string> Library

5