String in C++

A string in C++ is a type of object representing a collection of different characters.

C++ provides two types of string representations. They are:

  1. C-style Character String
  2. String class introduced in C++

C-style Character String

C-style character string was first introduced in C, which also supported in C++. This string is a one-dimensional character array that holds a character sequence which is terminated by a null character '\0'. When you create a C-style character string to keep “Hello,” it will contain the characters, ‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0.’ The compiler will include a character “\0” in the end by default.

Here, is an Example to see how you can use the character array to create and store a C-style character string in a variable:


#include <iostream>
using namespace std;

int main()
{
    char greet[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

    cout << "This is a greeting message: ";

    cout << greet << endl;

    return 0;
}
Output
This is a greeting message: Hello

String class introduced in C++

C++ follows the OOPs concept which allows representing the string as an object of the C++ String class (std:: string). The class allows us to declare a string variable quickly, and store any sequence of characters in it.

The following example shows the use of string with the help of the String class:


#include <iostream>
using namespace std;

int main()
{

    string greet = "Hello World";
    cout << "This is a greeting message: ";
    cout << greet << endl;
}
Output
This is a greeting message: Hello World

C++ Built-In String Functions

The C++ String class provides many built-in functions to manipulate strings. Here, we will go through some primary functions along with examples.

C++ String Input Functions

The input functions help to add or remove a character to a string. There are three widely used input functions in C++:

  1. getline() — This function is used to read and store a string that the user enters through the input stream.
  2. Here, is an Example to see how you can use the getline() function to read from the input stream:

    
    #include <iostream>
    using namespace std;
    
    int main() {
      char profession[12];
      
      cout << "Enter your profession: ";
      // We will take a maximum of 12 characters as input
      cin.getline(profession, 12);
      
      cout << "Your profession is: " << profession;
      
      return 0;
    }
    

    After running the program, assume this is the input given by the User:

    Enter your profession: Software Engineer

    The output will look like this:

    Enter your profession: Software Engineer Your profession is: Software Engineer
  3. push_back() — This function is used to input a new character to the string's end.
  4. Example
    
    #include <iostream>
    using namespace std;
    
    int main()
    {
        string name = "Hello";
    
        cout << "Name before using push_back: " << name << endl;
    
        // Let's add the word "World" at the end of the above string
        name.push_back(' ');
        name.push_back('W');
        name.push_back('o');
        name.push_back('r');
        name.push_back('l');
        name.push_back('d');
    
        cout << "Name after using push_back: " << name << endl;
        return 0;
    }
    
    Output
    Name before using push_back: Hello
    Name after using push_back: Hello World
  5. pop_back() — This function is used to remove or pops out (deletes) a string's last character.
  6. Example
    
    #include <iostream>
    using namespace std;
    
    int main()
    {
        string name = "Hello";
    
        cout << "Name before using pop_back: " << name << endl;
    
        // using the pop_back() function
        name.pop_back();
    
        cout << "Name after using pop_back: " << name << endl;
        return 0;
    }
    
    
    Output
    Name before using pop_back: Hello
    Name after using pop_back: Hell

C++ String Iterator Functions

The most commonly used String iterator functions are:

  1. begin() — This function returns the iterator to the beginning of the string.
  2. Example
    
    #include <iostream>
    using namespace std;
    
    int main()
    {
        string str = "Learning C++";
    
        // declaring an iterator
        string::iterator it;
    
        it = str.begin();
        cout << *it << " ";
        it++;
        cout << *it;
        return 0;
    }    
    
    Output
    L e
  3. end() — This function returns the iterator to the end of the string. The iterator will always point to the null character.
  4. Example
    
    #include <iostream>
    using namespace std;
    
    int main()
    {
        string str = "Programming";
    
        // declaring an iterator
        string::iterator it;
    
        it = str.end();
    
        cout << *it; // nothing will print because the iterator points to \0
        it--;
        cout << *it;
        it--;
    
        cout << *it;
        return 0;
    }
    
    Output
  5. rbegin() — This function returns a reverse iterator that points to the end.
  6. Example
    
    #include <iostream>
    using namespace std;
    
    int main()
    {
        string str = "Programming";
    
        // declaring a reverse iterator
        string::reverse_iterator rit;
    
        rit = str.rbegin();
    
        cout << *rit;
        rit++;
    
        cout << *rit;
        rit++;
    
        cout << *rit;
        return 0;
    }
    
    
    Output
    gni

    The difference between rbegin() and end() function is that the end() function points to the element next to the last element of the string while the rbegin() function points to the last element of a string.

  7. rend() — This function returns a reverse iterator that points to the start.
  8. Example
    
    #include <iostream>
    using namespace std;
    
    int main()
    {
        string str = "Learning C++";
    
        // declaring a reverse iterator
        string::reverse_iterator rit;
    
        rit = str.rend();
        rit--;
    
        cout << *rit;
        rit--;
    
        cout << *rit;
        rit--;
    
        cout << *rit;
    
        return 0;
    }
    
    Output
    Lea

Capacity Functions

The C++ string capacity functions help to work with the size and capacity of the string. The commonly used capacity functions are:

  1. capacity() — This function returns the capacity allocated to a string by the compiler.
  2. Example
    
    #include <iostream>
    using namespace std;
    
    int main()
    {
        string str = "C++ Programming";
    
        cout << "The capacity of string is: " << str.capacity() << endl;
    
        return 0;
    }   
    
    Output
    The capacity of string is: 15
  3. resize() — This function allows increasing or decreasing the size of the string.
  4. Example
    
    #include <iostream>
    using namespace std;
    
    int main()
    {
        string str = "C++ Programming";
    
        cout << "The original string is: " << str << endl;
    
        // We will keep only the first ten characters of the string
        str.resize(10);
    
        cout << "The string after using resize is: " << str << endl;
        return 0;
    }
    
    Output
    The original string is: C++ Programming
    The string after using resize is: C++ Progra
  5. length() — This function returns the size of the string.
  6. Example
    
    #include <iostream>
    using namespace std;
    
    int main()
    {
        string str = "Calculating length of the string";
    
        cout << "The length of string is: " << str.length() << endl;
    
        return 0;
    }    
    
    Output
    The length of string is: 32
  7. shrink_to_fit() — This function decreases the string's capacity and makes the capacity equal to the minimum to save memory.
  8. Example
    
    #include <iostream>
    using namespace std;
    
    int main()
    {
        string str = "Using shrink to fit function";
    
        // using resize
        str.resize(17);
    
        cout << "The capacity of string before using shrink_to_fit is: " << str.capacity() << endl;
    
        str.shrink_to_fit();
    
        cout << "The capacity of string after using shrink_to_fit is: " << str.capacity() << endl;
        return 0;
    }
    
    Output
    The capacity of string before using shrink_to_fit is: 28
    The capacity of string after using shrink_to_fit is: 17

Manipulating Functions

The manipulating functions allow to manipulate a string. The commonly used manipulating functions are:

  1. copy(“char array”, len, pos) — This function is used to copy one substring to the other string which is in the function's arguments. It takes three arguments: target character array, length to be copied, and starting position in the string to start copying.
  2. Example
    
    #include <iostream>
    using namespace std;
    
    int main()
    {
        string str1 = "Using copy function";
        char str2[10];
    
        // copying nine chars starting from index 5
        str1.copy(str2, 9, 5);
    
        // The last character of a char array should be \0
        str2[9] = '\0';
    
        cout << "The copied string is: " << str2;
        return 0;
    }    
    
    Output
    The copied string is: copy fun
  3. swap() — This function is used to swap one string with another.
  4. Example
    
    #include <iostream>
    using namespace std;
    
    int main()
    {
        string fruit1 = "Apple";
        string fruit2 = "Orange";
    
        cout << "Before swap - fruit 1 is: " << fruit1 << endl;
        cout << "Before swap - fruit 2 is: " << fruit2 << endl
             << endl;
    
        // swapping
        fruit1.swap(fruit2);
    
        cout << "After swap - fruit 1 is: " << fruit1 << endl;
        cout << "After swap - fruit 2 is: " << fruit2 << endl;
        return 0;
    }
    
    Output
    Before swap - fruit 1 is: Apple
    Before swap - fruit 2 is: Orange

    After swap - fruit 1 is: Orange
    After swap - fruit 2 is: Apple