The Wayback Machine - https://web.archive.org/web/20240921013643/https://www.geeksforgeeks.org/stdstring-class-in-c/
Open In App

std::string class in C++

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

C++ has in its definition a way to represent a sequence of characters as an object of the class. This class is called std:: string. The string class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character.

String vs Character Array

String

Char Array

 A string is a class that defines objects that be represented as a stream of characters. A character array is simply an array of characters that can be terminated by a null character.
In the case of strings, memory is allocated dynamically. More memory can be allocated at run time on demand. As no memory is preallocated, no memory is wasted. The size of the character array has to be allocated statically, more memory cannot be allocated at run time if required. Unused allocated memory is also wasted
As strings are represented as objects, no array decay occurs. There is a threat of array decay in the case of the character array. 
Strings are slower when compared to implementation than character array. Implementation of character array is faster than std:: string. 
String class defines a number of functionalities that allow manifold operations on strings. Character arrays do not offer many inbuilt functions to manipulate strings.

Operations on Strings

1) Input Functions

Function Definition
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. 

Example:

CPP




// C++ Program to demonstrate the working of
// getline(), push_back() and pop_back()
#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 : 

Time Complexity: O(1)

Space Complexity: O(n) where n is the size of the string

2) Capacity Functions

Function Definition
capacity() This function returns the capacity allocated to the string, which can be equal to or more than the size of the string. Additional space is allocated so that when the new characters are added to the string, the operations can be done efficiently.
resize() This function changes the size of the string, the size can be increased or decreased.
length() This function finds the length of the string.
shrink_to_fit() This function decreases the capacity of the string and makes it equal to the minimum capacity of the string. This operation is useful to save additional memory if we are sure that no further addition of characters has to be made.

Example:

CPP




// C++ Program to demonstrate the working of
// capacity(), resize() and shrink_to_fit()
#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

Time Complexity: O(1)

Space Complexity: O(n) where n is the size of the string

3) Iterator Functions

Function Definition
begin() This function returns an iterator to the beginning of the string.
end() This function returns an iterator to the next to the end of the string.
rbegin() This function returns a reverse iterator pointing at the end of the string.
rend() This function returns a reverse iterator pointing to the previous of beginning of the string.
cbegin() This function returns a constant iterator pointing to the beginning of the string, it cannot be used to modify the contents it points-to.
cend() This function returns a constant iterator pointing to the next of end of the string, it cannot be used to modify the contents it points-to.
crbegin() This function returns a constant reverse iterator pointing to the end of the string, it cannot be used to modify the contents it points-to.
crend() This function returns a constant reverse iterator pointing to the previous of beginning of the string, it cannot be used to modify the contents it points-to.

Algorithm:

  1. Declare a string
  2. Try to iterate the string using all types of iterators
  3. Try modification of the element of the string.
  4. Display all the iterations.

Example:

CPP




// C++ Program to demonstrate the working of
// begin(), end(), rbegin(), rend(), cbegin(), cend(), crbegin(), crend()
#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

Time Complexity: O(1)

Space Complexity: O(n) where n is the size of the string

4) Manipulating Functions:

Function Definition
copy(“char array”, len, pos)  This function copies the substring in the target character array mentioned in its arguments. It takes 3 arguments, target char array, length to be copied, and starting position in the string to start copying.
swap() This function swaps one string with another

Example:

CPP




// C++ Program to demonstrate the working of
// copy() and swap()
#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

Must Read: C++ String Class and its Applications

 



Previous Article
Next Article

Similar Reads

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
std::string::length, std::string::capacity, std::string::size in C++ STL
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 &lt;string&gt; String Functionalities The
6 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
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
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
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
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
Difference between std::set::lower_bound and std::lower_bound in C++
Prerequisite: Random-access Iterators in C++, Bidirectional Iterators in C++. std::lower_bound in C++: The lower_bound() method in C++ is used to return an iterator pointing to the first element in the range [first, last) which has a value not less than the given value. This means that the function returns the index of the next smallest number just
4 min read
Difference between std::set::upper_bound and std::upper_bound in C++
Prerequisites: Random-access Iterators, Bidirectional Iterators Sets are a type of associative container in which each element has to be unique because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element. Functions
4 min read
std::tuple_element() and std::tuple_size() in C++ with Examples
A tuple is an object that can hold a number of elements. The elements can be different data types. The elements of tuples are initialized as arguments in the order in which they will be accessed. The functions- tuple_element() and tuple_size() are only defined for elements using tuple_like interface. tuple_element():The C++ function tuple_element(a
2 min read
std::tuple, std::pair | Returning multiple values from a function using Tuple and Pair in C++
There can be some instances where you need to return multiple values (maybe of different data types ) while solving a problem. One method to do the same is by using pointers, structures or global variables, already discussed here There is another interesting method to do the same without using the above methods,  using tuples (for returning multipl
2 min read
std::regex_match, std::regex_replace() | Regex (Regular Expression) In C++
Regex is the short form for “Regular expression”, which is often used in this way in programming languages and many different libraries. It is supported in C++11 onward compilers.Function Templates used in regex regex_match() -This function return true if the regular expression is a match against the given string otherwise it returns false. C/C++ C
3 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::replace and std::replace_if in C++
std::replace Assigns new_value to all the elements in the range [first, last) that compare to old_value. The function use operator == to compare the individual elements to old_value Function Template : void replace (ForwardIterator first, ForwardIterator last, const T&amp; old_value, const T&amp; new_value) first, last : Forward iterators to the in
4 min read
std::remove, std::remove_if in c++
std :: remove It is defined in &lt;algorithm&gt; library. It removes value from range. Transforms the range [first,last) into a range with all the elements that compare equal to val removed, and returns an iterator to the new end of that range. The function cannot alter the properties of the object containing the range of elements (i.e., it cannot
4 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&gt;=size. std::basic_string::at throws std::out_of_range if pos &gt;= size().std::bsic_string::operator[] throws no exception and pr
2 min read
std::find_if , std::find_if_not in C++
std :: find_if and std :: find_if_not are algorithm functions in C++ Standard Library in &lt;algorithm&gt; header file. These functions provide an efficient way to search for an element in a container using a predicate function. std :: find_if This function returns an iterator to the first element in the range [first, last) for which pred(Unary Fun
3 min read
std::next vs std::advance in C++
std::advance and std::next are used to advance the iterator by a certain position, such that we can make the iterator point to a desired position. Although both have same purpose, but their implementation is different from each other. This makes it important for us to understand the difference between the two. In C++11, std::next() will advance by
3 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::stoul and std::stoull in C++
std::stoul Convert string to unsigned integer. Parses str interpreting its content as an integral number of the specified base, which is returned as an unsigned long value. unsigned long stoul (const string&amp; str, size_t* idx = 0, int base = 10); Parameters : str : String object with the representation of an integral number. idx : Pointer to an
3 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::vector::resize() vs. std::vector::reserve()
In C++, vectors are dynamically resizable arrays provided by STL. They can automatically change their size according to the number of elements and users also can change its size using the std::vector::resize()and std::vector::reserve(). But there is some difference in how these functions works. In this article, we will learn what are the difference
5 min read
Why Should We Not Derive from C++ std::string Class?
In C++, we might sometimes think of deriving from the std::string class to use its existing functionality while adding our own enhancements. However, deriving from std::string is generally discouraged due to several technical and design concerns. In this article, we will learn why inheriting from std::string is problematic and discuss some practica
4 min read
std::any Class in C++
any is one of the newest features of C++17 that provides a type-safe container to store single value of any type. In layman's terms, it is a container which allows one to store any value in it without worrying about the type safety. It acts as an extension to C++ by mimicking behaviour similar to an object type in .NET/Java or void* type in C langu
6 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
Practice Tags :