The std::string class is the standard C++ library class used to represent and manipulate strings. It automatically manages memory, making string handling safer and more convenient than using character arrays.
- Dynamically manages memory without requiring manual allocation or null-termination.
- Provides a wide range of built-in functions for creating, accessing, modifying, comparing, and searching strings.
- Declared in the <string> header and part of the std namespace.
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "GeeksforGeeks";
cout << str;
return 0;
}
Output
GeeksforGeeks
Explanation: The program creates a std::string object named str, initializes it with "GeeksforGeeks", and prints the string.
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.
| Function | Description |
|---|---|
| getline() | Reads an entire line from the input stream. |
| push_back() | Appends a character to the end of the string. |
| pop_back() | Removes the last character from the string. |
#include <iostream>
#include <string> // for string class
using namespace std;
// Driver Code
int main()
{
// Declaring string
string str;
// Taking string input using getline()
getline(cin, str);
// Displaying string
cout << "The initial string is : ";
cout << str << endl;
// Inserting a character
str.push_back('s');
// Displaying string
cout << "The string after push_back operation is : ";
cout << str << endl;
// Deleting a character
str.pop_back();
// Displaying string
cout << "The string after pop_back operation is : ";
cout << str << endl;
return 0;
}
Output
The initial string is : The string after push_back operation is : s The string after pop_back operation is :
Explanation: getline() reads the complete line, push_back() adds a character to the end, and pop_back() removes the last character.
- Time Complexity: O(1)
- Space Complexity: O(n) where n is the size of the string
Capacity Functions
These functions provide information about the size and memory allocated to a string.
| Function | Description |
|---|---|
| capacity() | Returns the current capacity of the string. |
| resize() | Changes the size of the string. |
| length() | Returns the number of characters in the string. |
| shrink_to_fit() | Reduces the string's capacity to match its size. |
#include <iostream>
#include <string> // for string class
using namespace std;
int main()
{
// Initializing string
string str = "geeksforgeeks is for geeks";
// Displaying string
cout << "The initial string is : ";
cout << str << endl;
// Resizing string using resize()
str.resize(13);
// Displaying string
cout << "The string after resize operation is : ";
cout << str << endl;
// Displaying capacity of string
cout << "The capacity of string is : ";
cout << str.capacity() << endl;
// Displaying length of the string
cout << "The length of the string is :" << str.length()
<< endl;
// Decreasing the capacity of string
// using shrink_to_fit()
str.shrink_to_fit();
// Displaying string
cout << "The new capacity after shrinking is : ";
cout << str.capacity() << endl;
return 0;
}
Output
The initial string is : geeksforgeeks is for geeks The string after resize operation is : geeksforgeeks The capacity of string is : 26 The length of the string is :13 The new capacity after shrinking is : 13
Explanation: resize() changes the number of characters, while capacity() and shrink_to_fit() help manage memory efficiently.
Iterator Functions
Iterator functions allow traversal of a string in both forward and reverse directions.
| Function | Description |
|---|---|
| begin() | Returns an iterator to the first character. |
| end() | Returns an iterator to the position after the last character. |
| rbegin() | Returns a reverse iterator to the last character. |
| rend() | Returns a reverse iterator to the position before the first character. |
| cbegin() | Returns a constant iterator to the first character. |
| cend() | Returns a constant iterator to the position after the last character. |
| crbegin() | Returns a constant reverse iterator to the last character. |
| crend() | Returns a constant reverse iterator to the position before the first character. |
#include <iostream>
#include <string> // for string class
using namespace std;
// Driver Code
int main()
{
// Initializing string`
string str = "geeksforgeeks";
// Declaring iterator
std::string::iterator it;
// Declaring reverse iterator
std::string::reverse_iterator it1;
cout<<"Str:"<<str<<"\n";
// Displaying string
cout << "The string using forward iterators is : ";
for (it = str.begin(); it != str.end(); it++){
if(it == str.begin()) *it='G';
cout << *it;
}
cout << endl;
str = "geeksforgeeks";
// Displaying reverse string
cout << "The reverse string using reverse iterators is "
": ";
for (it1 = str.rbegin(); it1 != str.rend(); it1++){
if(it1 == str.rbegin()) *it1='S';
cout << *it1;
}
cout << endl;
str = "geeksforgeeks";
//Displaying String
cout<<"The string using constant forward iterator is :";
for(auto it2 = str.cbegin(); it2!=str.cend(); it2++){
//if(it2 == str.cbegin()) *it2='G';
//here modification is NOT Possible
//error: assignment of read-only location
//As it is a pointer to the const content, but we can inc/dec-rement the iterator
cout<<*it2;
}
cout<<"\n";
str = "geeksforgeeks";
//Displaying String in reverse
cout<<"The reverse string using constant reverse iterator is :";
for(auto it3 = str.crbegin(); it3!=str.crend(); it3++){
//if(it2 == str.cbegin()) *it2='S';
//here modification is NOT Possible
//error: assignment of read-only location
//As it is a pointer to the const content, but we can inc/dec-rement the iterator
cout<<*it3;
}
cout<<"\n";
return 0;
}
//Code modified by Balakrishnan R (rbkraj000)
Output
Str:geeksforgeeks The string using forward iterators is : Geeksforgeeks The reverse string using reverse iterators is : Skeegrofskeeg The string using constant forward iterator is :geeksforgeeks The reverse string using constant reverse iterator is :skeegrofskeeg
Explanation: Normal iterators allow modification of characters, whereas constant iterators provide read-only access.
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.