The std::string class is part standard library and is used to store and manipulate sequences of characters. It is declared in the <string> header.
- Manages memory automatically and supports dynamic resizing.
- Provides functions for accessing, modifying, comparing, and searching strings.
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "GeeksforGeeks";
cout << str;
return 0;
}
Output
GeeksforGeeks
Explanation: The program creates a string object named str and prints its value.
Creating and Initializing Strings
Strings can be created in multiple ways.
string str1 = "GeeksforGeeks";
string str2("C++");
string str3;
Explanation: str1 and str2 are initialized with values, while str3 is an empty string.
Common String Operations
The std::string class provides several member functions for performing common string operations.
Input Functions
These functions are used to read or modify the contents of a string.
- getline(): Reads a complete line, including spaces.
- push_back(): Adds a character at the end.
- pop_back(): Removes the last character.
#include <iostream>
#include <string>
using namespace std;
int main() {
// Initialize a string
string str = "GeeksforGeeks";
cout << "Original String: " << str << '\n';
// Add a character
str.push_back('!');
cout << "After push_back: " << str << '\n';
// Remove the last character
str.pop_back();
cout << "After pop_back: " << str << '\n';
return 0;
}
Output
Original String: GeeksforGeeks After push_back: GeeksforGeeks! After pop_back: GeeksforGeeks
Explanation: The program initializes a string, adds ! at the end using push_back(), and removes the last character using pop_back().
Capacity Functions
These functions provide information about the size and memory allocated to a string.
- size() / length(): Returns the number of characters.
- capacity(): Returns the current character capacity without reallocation.
- resize() :Changes the string's length.
- shrink_to_fit(): Requests a reduction in capacity.
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "geeksforgeeks is for geeks";
// Resize the string
str.resize(13);
cout << "After resize: " << str << '\n';
// Display length
cout << "Length: " << str.length() << '\n';
// Check capacity
cout << boolalpha;
cout << "Capacity >= length: "
<< (str.capacity() >= str.length()) << '\n';
// Request capacity reduction
str.shrink_to_fit();
cout << "Capacity sufficient after shrink: "
<< (str.capacity() >= str.length());
return 0;
}
Output
After resize: geeksforgeeks Length: 13 Capacity >= length: true Capacity sufficient after shrink: true
Explanation: The resize() function shortens the string. The capacity() function reports its storage capacity, while shrink_to_fit() requests a reduction in unused capacity.
Iterator Functions
Iterator functions allow traversal of a string in both forward and reverse directions.
- begin() / end(): Returns forward iterators.
- rbegin() / rend(): Returns reverse iterators.
- cbegin() / cend(): Returns constant forward iterators.
- crbegin() / crend(): Returns constant reverse iterators.
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Geeks";
// Forward iteration
cout << "Forward: ";
for (auto it = str.begin(); it != str.end(); ++it)
cout << *it;
// Reverse iteration
cout << "\nReverse: ";
for (auto it = str.rbegin(); it != str.rend(); ++it)
cout << *it;
// Constant iteration
cout << "\nConst: ";
for (auto it = str.cbegin(); it != str.cend(); ++it)
cout << *it;
return 0;
}
Output
Forward: Geeks Reverse: skeeG Const: Geeks
Explanation: Forward iterators traverse from beginning to end, reverse iterators traverse backward, and constant iterators prevent modification through the iterator.
String Vs Character Array
Both std::string and character arrays are used to store text in C++, but they differ significantly in terms of memory management, flexibility, and available functionality.
| std::string | Character Array |
|---|---|
| Dynamically resizes as needed. | Has a fixed size decided at declaration. |
| Provides many built-in functions for string manipulation. | Requires C string functions for most operations. |
| Behaves like a normal C++ object without array decay. | Can undergo array decay when passed to functions. |
| Automatically manages memory. | Requires careful handling to avoid memory-related issues. |
| Slightly slower due to additional abstraction. | Generally faster because it works directly with memory. |
Limitations
Although std::string is flexible and easy to use, it has a few limitations.
- Uses slightly more memory than character arrays.
- Some operations may involve dynamic memory allocation.
- May not be suitable for highly memory-constrained applications.
Best Practices
Following these practices helps write cleaner and more efficient string-related code.
- Prefer std::string over C-style strings in modern C++.
- Use built-in member functions instead of manual string manipulation.
- Pass large strings by const reference to avoid unnecessary copying.

