The Wayback Machine - https://web.archive.org/web/20240921013614/https://www.geeksforgeeks.org/std-string-length-std-string-capacity-std-string-size-in-cpp-stl/
Open In App

std::string::length, std::string::capacity, std::string::size in C++ STL

Last Updated : 24 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Prerequisite: String in C++

String class is one of the features provided by the Standard template library to us, So it comes up with great functionality associated with it. With these Functionalities, we can perform many tasks easily. Let’s see a few of the functionalities string class provides.

Header File <string>

String Functionalities

There are many functionalities associated with string class but we will be focusing on only three of them, these are: 

  • std :: string :: length 
  • std :: string :: size
  • std :: string :: capacity
  • std :: string :: reserve()
  • std :: string :: shrink_to_fit()

All three functions are public member functions of the Class String. To know more about other functionalities in string class refer to a String in STL.

1. std::string::length

Returns the length of a string. This returns the exact no. of characters or bytes used and not the memory that is allocated at the backend. length member function never throws exceptions.

Syntax:

size_t std::string::length( )

Note: 

  1. size_t is a typedef version of unsigned int, as sizes cannot be negative.
  2. No parameters are passed, the string is identified with this pointer.

2. std::string::size

Returns the length of the string, in terms of bytes. This returns the exact no. of characters or bytes used and not the memory that is allocated at the backend. Both length and size are the same and return the same value but size can be used in any container like vector, list, etc whereas length is more associated with the string. size member function never throws exceptions.

Syntax:

size_t std::string::size( )

3. std::string::capacity

  • Returns the size of the storage space currently allocated in the Memory for that string object.
  • This does NOT return the exact no. of characters or bytes used but, the memory that is allocated at the backend.
  • Capacity is always GREATER THAN EQUAL TO size/length.
    • The extra space allows the string object to optimize its operations when new characters are added.
  • Capacity is NOT limited, as needed the capacity is increased by the compiler.
  • Capacity does not Reduce automatically, it needs to be done explicitly.

Syntax:

size_t std::string::capacity( );

Code:

C++




// C++ Program to demonstrate use of
// std::string::capacity
// std::string::size
// std::string::length
#include <iostream>
#include <string>
 
using namespace std;
 
int main()
{
    // empty str
    string str;
    cout << "str is : " << str << "\n";
    cout << "size: " << str.size()
         << " length: " << str.length()
         << " capacity: " << str.capacity() << "\n";
 
    // H - only one character
    str = "H";
    cout << "str is : " << str << "\n";
    cout << "size: " << str.size()
         << " length: " << str.length()
         << " capacity: " << str.capacity() << "\n";
 
    // Hello
    str = "Hello";
    cout << "str is : " << str << "\n";
    cout << "size: " << str.size()
         << " length: " << str.length()
         << " capacity: " << str.capacity() << "\n";
 
    // Hello with space added
    str = "Hello ";
    cout << "str is : " << str << "\n";
    cout << "size: " << str.size()
         << " length: " << str.length()
         << " capacity: " << str.capacity() << "\n";
 
    // one more modification
    str = "Hello GFG Reader";
    cout << "str is : " << str << "\n";
    cout << "size: " << str.size()
         << " length: " << str.length()
         << " capacity: " << str.capacity() << "\n";
 
    // Back to Hello
    str = "Hello";
    cout << "str is : " << str << "\n";
    cout << "size: " << str.size()
         << " length: " << str.length()
         << " capacity: " << str.capacity() << "\n";
 
    // reserve is basically request to compiler to change
    // the capacity decrease capacity
    str.reserve(7);
    cout << "str is : " << str << "\n";
    cout << "size: " << str.size()
         << " length: " << str.length()
         << " capacity: " << str.capacity() << "\n";
 
    // increase capacity
    str.reserve(35);
    cout << "str is : " << str << "\n";
    cout << "size: " << str.size()
         << " length: " << str.length()
         << " capacity: " << str.capacity() << "\n";
 
    return 0;
}


Output

str is : 
size: 0 length: 0 capacity: 0
str is : H
size: 1 length: 1 capacity: 1
str is : Hello
size: 5 length: 5 capacity: 5
str is : Hello 
size: 6 length: 6 capacity: 10
str is : Hello GFG Reader
size: 16 length: 16 capacity: 20
str is : Hello
size: 5 length: 5 capacity: 20
str is : Hello
size: 5 length: 5 capacity: 7
str is : Hello
size: 5 length: 5 capacity: 35

The above code demonstrates all the possible scenarios. The facts have also proven that Capacity >= size/length, then the capacity increases automatically as the size of the string crosses the previous capacity, then the capacity is never reduced back when the size goes down, but that can be done explicitly by the programmer using reserve function.

Time and Space Complexity

Functions Time Extra Space
str.size() O(1) O(1)
str.length() O(1) O(1)
str.capacity() O(1) O(1)

4. std::string::reserve

  • Reserves a specified amount of storage space in memory for the string object without changing its length or content. 
  • This function can be used to avoid multiple memory reallocations when appending characters to a string.
  • The function reserves the memory to accommodate at least the specified number of characters or bytes, but the actual capacity may be greater than that. 
  • If the requested capacity is less than or equal to the current capacity, the function has no effect.

Syntax:

void std::string::reserve(size_t new_cap);

Example:

C++




#include <iostream>
#include <string>
 
int main()
{
    std::string str;
    std::cout << "Before reserve(), capacity = "
              << str.capacity() << std::endl;
    str.reserve(100); // Reserve memory for 100 characters
    std::cout << "After reserve(), capacity = "
              << str.capacity() << std::endl;
    return 0;
}


Output

Before reserve(), capacity = 0
After reserve(), capacity = 100

5. std::string::shrink_to_fit

  • std::string::shrink_to_fit() reduces the capacity of the string object to fit its actual length, potentially saving memory. 
  • The function has no effect if the current capacity is already equal to or less than the actual length of the string.
  • The function can be used to release unused memory of a string object that was previously expanded with std::string::reserve(). 
  • Calling std::string::shrink_to_fit() can reduce the capacity to fit the actual string, potentially saving memory.

Syntax:

void std::string::shrink_to_fit();

Example:

C++




#include <iostream>
#include <string>
 
int main()
{
    std::string str = "Hello, World!";
    std::cout << "Before shrink_to_fit(), capacity = "
              << str.capacity() << std::endl;
    str.reserve(100); // Reserve memory for 100 characters
    std::cout << "After reserve(), capacity = "
              << str.capacity() << std::endl;
    str.shrink_to_fit(); // Shrink the capacity to fit the
                         // actual length
    std::cout << "After shrink_to_fit(), capacity = "
              << str.capacity() << std::endl;
    return 0;
}


Output

Before shrink_to_fit(), capacity = 13
After reserve(), capacity = 100
After shrink_to_fit(), capacity = 13


Similar Reads

Difference Between Size and Capacity of a Vector in C++ STL
In this article, we are going to study the difference between the size and capacity of a vector in C++ STL. The size of the vector is defined as the total number of elements present in the vector. Vector is a dynamic array so it changes with the user input, unlike the static arrays which we define with the subscript operators "[]" which remain cons
3 min read
std::fixed, std::scientific, std::hexfloat, std::defaultfloat in C++
Formatting in the standard C++ libraries is done through the use of manipulators, special variables or objects that are placed on the output stream. There are two types of floating point manipulators namely, fixed floating point and scientific floating point. These all are defined in header &lt;iostream&gt;. Use of precision : In the default floati
3 min read
vector capacity() function in C++ STL
The vector::capacity() function is a built-in function which returns the size of the storage space currently allocated for the vector, expressed in terms of elements. This capacity is not necessarily equal to the vector size. It can be equal to or greater, with the extra space allowing to accommodate for growth without the need to reallocate on eac
2 min read
std::istream_iterator and std::ostream_iterator in C++ STL
The STL is a very powerful library in C++. It is strongly built on the principles of template programming. The STL library has three main components : Containers: These classes define the data structures which are used to contain the data. The data may be stored in linked lists, or trees or arrays. The containers provided in the STL are vector, deq
6 min read
std::bitset::to_ullong and std::bitset::to_ulong in C++ STL
Bitset: A bitset is an array of bool but each Boolean value is not stored separately instead bitset optimizes the space such that each bool takes 1 bit space only, so space taken by bitset bs is less than that of bool bs[N] and vector bs(N). However, a limitation of bitset is, N must be known at compile time, i.e., a constant (this limitation is no
2 min read
std::minmax() and std::minmax_element() in C++ STL
C++ defined functions to get smallest and largest elements among 2 or in a container using different functions. But there are also functions that are used to get both smallest and largest element using a single function, "minmax()" function achieves this task for us. This function is defined in "algorithm" header file. This article would deal in it
4 min read
std::rotate vs std::rotate_copy in C++ STL
rotate in STL:It rotates the order of the elements in the range [first, last), in such a way that the element pointed by middle becomes the new first element, i, e, to the left. // Illustrating the use of rotate algorithm #include &lt;bits/stdc++.h&gt; using namespace std; // Driver Program int main() { vector&lt;int&gt; arr; // set some values: 1
2 min read
std::upper_bound and std::lower_bound for Vector in C++ STL
Click here for Set 1 and Set 2 of Vectors. Vector - upper_bound and lower_boundIterator lower_bound (Iterator first, Iterator last, const val) lower_bound returns an iterator pointing to the first element in the range [first,last) which has a value not less than 'val' and if the value is not present in the vector then it returns the end iterator. I
4 min read
std::oct , std::dec and std::hex in C++
This function is used to set the base to octal, decimal or hexadecimal. It sets the basefield format flag for the str stream to the specified base std::oct : When basefield is set to octal, integer values inserted into the stream are expressed in octal base (i.e., radix 8). For input streams, extracted values are also expected to be expressed in oc
2 min read
std::stod, std::stof, std::stold in C++
std::stod() : It convert string into double. Syntax: double stod( const std::string&amp; str, std::size_t* pos = 0 ); double stod( const std::wstring&amp; str, std::size_t* pos = 0 ); Return Value: return a value of type double Parameters str : the string to convert pos : address of an integer to store the number of characters processed. This param
3 min read
std::setbase, std::setw , std::setfill in C++
The useful input/output manipulators are std::setbase, std::setw and std::setfill. These are defined in and are quite useful functions. std::base : Set basefield flag; Sets the base-field to one of its possible values: dec, hex or oct according to argument base.Syntax : std::setbase (int base);decimal : if base is 10hexadecimal : if base is 16octal
3 min read
std::string::remove_copy(), std::string::remove_copy_if() in C++
remove_copy() It is an STL function in c++ which is defined in algorithm library. It copies the elements in the range [first, last) to the range beginning at result, except those elements that compare equal to given elements. The resulting range is shorter than [first,last) by as many elements as matches in the sequence, which are "removed". The re
4 min read
std::string::replace_copy(), std::string::replace_copy_if in C++
replace_copy replace_copy() is a combination of copy() and replace(). It copies the elements in the range [first, last) to the range beginning at result, replacing the appearances of old_value by new_value.The range copied is [first, last), which contains all the elements between first and last, including the element pointed by first but not the el
4 min read
std::string::append vs std::string::push_back() vs Operator += in C++
To append characters, you can use operator +=, append(), and push_back(). All of them helps to append character but with a little difference in implementation and application. Operator += : appends single-argument values. Time complexity : O(n)append() : lets you specify the appended value by using multiple arguments. Time complexity: O(n)push_back
6 min read
Find and print duplicate words in std::vector&lt;string&gt; using STL functions
Consider an array of string and find duplicate words in that array and print that duplicate words if exist.Examples: Input : { "welcome", "to", "geeks", "for", "geeks" } Output : geeks Input : { "reduce", "reuse", "recycle", "reduce", "reuse", "recycle", " recycle" } Output : recycle reduce reuse Input : { "Go", "Green" } Output : No Duplicate word
2 min read
std::list::sort in C++ STL
Lists are containers used in C++ to store data in a non contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists. list::sort() sort() function is used to sort the elements of the container by changing their positi
2 min read
std::forward_list::sort() in C++ STL
Forward list in STL implements singly linked list. Introduced from C++11, forward list are useful than other containers in insertion, removal and moving operations (like sort) and allows time constant insertion and removal of elements.It differs from list by the fact that forward list keeps track of location of only next element while list keeps tr
3 min read
std :: reverse_copy in C++ STL
C++ STL provides a function that copies the elements from the given range but in reverse order. Below is a simple program to show the working of reverse_copy(). Examples: Input : 1 2 3 4 5 6 7 8 9 10 Output : The vector is: 10 9 8 7 6 5 4 3 2 1 The function takes three parameters. The first two are the range of the elements which are to be copied a
2 min read
std::hash class in C++ STL
The hash class is default constructible, which means that one can construct this object without any arguments or initialization values. It is used to get the hash value of the argument that is being passed to it. If the argument doesn't change, the value doesn't change either.Syntax: template &lt;class T&gt; struct hash; Syntax to create object: ha
2 min read
C++ Std vs Stl
The full form of std is standard and it is a namespace. All the identifiers are declared inside the std namespace, in other words, a namespace provides scope to identifiers such as function names, variable names, etc. defined inside it. It is a feature especially available in C++ and is not present in C. The std keyword is used along with the space
4 min read
std::transform() in C++ STL (Perform an operation on all elements)
Consider the problem of adding contents of two arrays into a third array. It is given that all arrays are of same size. Following is simple C++ program without transform(). C/C++ Code // A C++ code to add two arrays #include &lt;bits/stdc++.h&gt; using namespace std; int main() { int arr1[] = {1, 2, 3}; int arr2[] = {4, 5, 6}; int n = sizeof(arr1)/
2 min read
std::partition in C++ STL
C++ has a class in its STL algorithms library which allows us easy partition algorithms using certain inbuilt functions. Partition refers to act of dividing elements of containers depending upon a given condition. Partition operations :1. partition(beg, end, condition) :- This function is used to partition the elements on basis of condition mention
5 min read
Different methods to copy in C++ STL | std::copy(), copy_n(), copy_if(), copy_backward()
Various varieties of copy() exist in C++ STL that allows to perform the copy operations in different manners, all of them having their own use. These all are defined in header &lt;algorithm&gt;. This article introduces everyone to these functions for usage in day-to-day programming. 1. copy(strt_iter1, end_iter1, strt_iter2) : The generic copy func
5 min read
Quickly merging two sorted arrays using std::merge() in C++ STL
C++ program to merge two sorted arrays of length 'n' and 'm' respectively in sorted order. Examples: Input: A[] = {3, 6, 9} B[] = {2, 7, 11} Output: C[] = {2, 3, 6, 7, 9, 11} Input: A[] = {1, 1, 3, 6, 9} B[] = {1, 2, 7, 11, 11} Output: C[] = {1, 1, 1, 2, 3, 6, 7, 9, 11, 11} We have discussed other approaches in below posts Merge two sorted arrays w
2 min read
std::count() in C++ STL
std::count() returns the number of occurrences of an element in a given range. Returns the number of elements in the range [first, last) that compare equal to val. If the val is not found at any occurrence then it returns 0(Integer value). // Returns count of occurrences of value in // range [begin, end] int count(Iterator first, Iterator last, T
2 min read
std::includes() in C++ STL
includes() is a C++ function that can be used to recognize if all the numbers in a container, also exist in other containers. It helps to check whether a set is a subset of another set or not considering the set is ordered. The elements are expected to be in sorted order. This function is defined in &lt;algorithm&gt; header file. There are two impl
4 min read
std::is_permutation in C++ STL
The C++ function std::algorithm::is_permutation() tests whether a sequence is permutation of other or not. It uses operator == for comparison. This function was defined in C++11. Syntax: template &lt;class ForwardIterator1, class ForwardIterator2 &gt;bool is_permutation(ForwardIterator1 first1, ForwardIterator1 last1,ForwardIterator2 first2);first1
3 min read
std::sort() in C++ STL
std::sort() is an STL function that is used to sort the given range in desired order. It provides a simple and efficient way to sort the data in C++ but it only works on data structure which have random access to its elements such as vectors and arrays. It is defined inside &lt;algorithm&gt; header file. Syntaxstd::sort (first, last, comp);Paramete
4 min read
Difference between std::swap and std::vector::swap
The std::swap is a general function used to exchange the given values whereas the std::vector::swap is a specialized function that can swap all the contents of two different vector containers.Below are some major key differences between std::swap and std::vector::swap, std::swapstd::vector::swapThe std::swap() is a built-in function in C++ STL whic
3 min read
Difference between std::quick_exit and std::abort
std::quick_exit() It Causes normal program termination to occur without completely cleaning the resources. Syntax : void quick_exit(int exit_code) no except; In case of execution of threads the codes becomes complex and knowing the execution of threads is hard. While one the thread might be waiting for a process to end while the other thread is wai
3 min read
Article Tags :
Practice Tags :