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.
Syntax
#include <string>
std::string str;
Here,
- std::string represents the string class.
- str is the string object.
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.
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. |
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() | This function is used to store a stream of characters as entered by the user in the object memory. |
| push_back() | This function is used to input a character at the end of the string. |
| pop_back() | Introduced from C++11(for strings), this function is used to delete 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;
// Driver Code
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.
- Time Complexity: O(1)
- Space Complexity: O(n) where n is the size of the string
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. |
Algorithm
- Declare a string
- Try to iterate the string using all types of iterators
- Try modification of the element of the string.
- Display all the iterations.
#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.
- Time Complexity: O(1)
- Space Complexity: O(n) where n is the size of the string
String Manipulating Functions
These functions modify or exchange string contents.
| Function | Definition |
|---|---|
| copy("char array", len, pos) | Copies a substring into a character array using the target array, length, and starting position. |
| swap() | This function swaps one string with another |
#include <iostream>
#include <string> // for string class
using namespace std;
// Driver Code
int main()
{
// Initializing 1st string
string str1 = "geeksforgeeks is for geeks";
// Declaring 2nd string
string str2 = "geeksforgeeks rocks";
// Declaring character array
char ch[80];
// using copy() to copy elements into char array
// copies "geeksforgeeks"
str1.copy(ch, 13, 0);
// Displaying char array
cout << "The new copied character array is : ";
cout << ch << endl;
// Displaying strings before swapping
cout << "The 1st string before swapping is : ";
cout << str1 << endl;
cout << "The 2nd string before swapping is : ";
cout << str2 << endl;
// using swap() to swap string content
str1.swap(str2);
// Displaying strings after swapping
cout << "The 1st string after swapping is : ";
cout << str1 << endl;
cout << "The 2nd string after swapping is : ";
cout << str2 << endl;
return 0;
}
Output
The new copied character array is : geeksforgeeks The 1st string before swapping is : geeksforgeeks is for geeks The 2nd string before swapping is : geeksforgeeks rocks The 1st string after swapping is : geeksforgeeks rocks The 2nd string after swapping is : geeksforgeeks is for geeks
Explanation: copy() copies characters into a character array, while swap() exchanges the contents of two strings without copying them.
Advantages of std::string
The std::string class provides several advantages over traditional character arrays.
- Automatically manages memory.
- Easy to resize and modify.
- Rich set of built-in member functions.
- Supports comparison, concatenation, and searching.
- Safer and easier to use than character arrays.
Related Artilce: C++ String Class and its Applications