std::string::length, std::string::capacity, std::string::size in C++ STL
Last Updated :
24 Mar, 2023
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:
- size_t is a typedef version of unsigned int, as sizes cannot be negative.
- 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;
}
Outputstr 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;
}
OutputBefore 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;
}
OutputBefore shrink_to_fit(), capacity = 13
After reserve(), capacity = 100
After shrink_to_fit(), capacity = 13
Similar Reads
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
6 min read
std::basic_string::at vs std::basic_string::operator[]
std::basic_string::at, std::basic_string::operator[]Both at() and operator[] can be used to access an element in the string. But there exists one difference between them on how to handle exceptional condition when pos>=size. std::basic_string::at throws std::out_of_range if pos >= size().std::
2 min read
Vector size vs capacity in C++ STL
In C++, the size of a vector is the number of elements in the vector. It can grow or shrink as elements are added or removed. To store these elements, each vector is allocated some memory. This total allocated memory is called the capacity of the vector.The following table lists the primary differen
3 min read
Difference between concatenation of strings using (str += s) and (str = str + s)
A string is a collection of characters. For example, "GeeksforGeeks" is a string. C++ provides primitive data types to create a string. The string can also be initialized at the time of declaration. Syntax: string str; string str = "GeeksforGeeks" Here, "GeeksforGeeks" is a string literal. This arti
15+ min read
string::rbegin() and string::rend() in C++
The std::string::rbegin() and std::string::rend() functions in C++ are used to fetch the reverse iterators to the string. They are the member function of std::string and are used when we want to iterate the string in reverse. In this article, we will learn how to use string::rbegin() and string::ren
2 min read
5 Different Methods to Find Length of a String in C++
The string is a sequence of characters or an array of characters. The declaration and definition of the string using an array of chars are similar to the declaration and definition of an array of any other data type. Examples: Input: "Geeksforgeeks" Output: 13 Input: "Geeksforgeeks \0 345" Output: 1
4 min read
std::stod, std::stof, std::stold in C++
std::stod() : It convert string into double. Syntax: double stod( const std::string& str, std::size_t* pos = 0 ); double stod( const std::wstring& 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 st
3 min read
Convert String to size_t in C++
To convert String to size_t in C++ we will use stringstream, It associates a string object with a stream allowing you to read from the string as if it were a stream (like cin). We must include the stream header file in order to use stringstream. When parsing input, the stringstream class comes in qu
1 min read
How to write long strings in Multi-lines C/C++?
Image a situation where we want to use or print a long long string in C or C++, how to do this? In C/C++, we can break a string at any point in the middle using two double quotes in the middle. Below is a simple example to demonstrate the same. C #include<stdio.h> int main() { // We can put tw
2 min read
std::basic_string::max_size in C++
std::basic_string::max_size is used to compute the maximum number of elements the string is able to hold due to system or library implementation limitations. size_type max_size() const; Parameters : None Return value : Maximum number of characters Exceptions : None CPP // CPP program to compute the
1 min read