A string is considered as a data type and is usually coded as an array of data structures of bytes or characters that is used to store a series of elements, basically characters, using some character encoding.

CPP Strings With Examples

Conceptually, it is similar to the character array in C language, but instead has a dedicated class in C++, and that dedicated class has various useful member functions that allow better and more sophisticated manipulation of the string data structure over character arrays.

One more main advantage of using strings over character arrays, which by the way can still be used in C++, is that strings use dynamic memory allocation. This means you do not have to create your variable with a fixed size during initialization that you will not be able to change throughout the whole program.

However, instead, a string can easily be resized, concatenated, shrunk, and manipulated during runtime.

Getting started

To use the string class in C++, an extra header needs to be included:
#include <string>

Creating your first string:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    /* create variable of type string */
    string helloWorld = "Hello World!";

    /* print out string value */
    cout << "My string value is: " << helloWorld << endl ;

    return 0;
}

Output:

My string value is Hello World!

Accessing Elements of String

1. Using [] operator

The [] operator just like in arrays or vectors gives you access to the element/character at a given index. However, if an index out of range is used, your program might crash.

Example:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    /* create variable of type string */
    string HelloWorld = "Hello World!";

    /* print input string */
    cout << "Input string: " << HelloWorld << endl << endl;

    /* print character at index 3 */
    cout << "Character at index 3: " << HelloWorld[3] << endl;

    /* print character at index 6 */
    cout << "Character at index 6: " << HelloWorld[6] << endl;

    /* print character at index 8 */
    cout << "Character at index 8: " << HelloWorld[8] << endl;

    return 0;
}

Output:

Input string: Hello World!

Character at index 3: l
Character at index 6: W
Character at index 8: r

2. Using at() function

This function has similar functionality as the [] operator and additionally checks whether the given index is out of range or not and throws an exception if out of range.

Example:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    /* create variable of type string */
    string HelloWorld = "Hello World!";

    /* print input string */
    cout << "Input string: " << HelloWorld << endl << endl;

    /* print character at index 3 */
    cout << "Character at index 3: " << HelloWorld.at(3) << endl;

    /* print character at index 6 */
    cout << "Character at index 6: " << HelloWorld.at(6) << endl;

    /* print character at index 8 */
    cout << "Character at index 8: " << HelloWorld.at(8) << endl;

    return 0;
}

Output:

Input string: Hello World!

Character at index 3: l
Character at index 6: W
Character at index 8: r

3. back()__ starting C++11

This function returns a reference to the last character in your string.

4. front()__ starting C++11

This function returns a reference to the first character in your string.

Example:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    /* create variable of type string */
    string HelloWorld = "gello World?";

    /* print input string */
    cout << "Input string: " << HelloWorld << endl;

    /* modify last character */
    HelloWorld.back() = '!';

    /* modify first character */
    HelloWorld.front() = 'H';

    /* print string after modifications */
    cout << "Output string: " << HelloWorld << endl;

    return 0;
}

Output:

Input string: Hello World?
Output string: Hello World!

Input Functions

1. getline()

This function is used to input whole lines or sentences into a string.
You can definitely use the input stream function “cin” to input strings but it will only allow you to input one word while the getline function reads till a new line is found.

Example:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string name;
    cout << "Enter your full name: " ; /* inputting string using cin */ cin >> name;

    cout << "Your full name is: " << name << endl;
    return 0;
}

Output:

Enter your full name: Foo Bar
Your full name is: Foo

Example using getline function:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string name;
    cout << "Enter your full name: " ;

    /* inputting string using getline */
    getline(cin, name);

    cout << "Your full name is: " << name << endl;
    return 0;
}

Output:

Enter your full name: Foo Bar
Your full name is: Foo Bar

2. push_back()

This function allows you to append characters to the end of your string.

Example:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string name;
    cout << "Enter you full name: " ;
    getline(cin, name);

    /* append one character */
    name.push_back('r');

    cout << "Your full name is: " << name << endl;
    return 0;
}

Output:

Enter your full name: Foo Ba
Your full name is: Foo Bar

3. pop_back()__ starting C++11

This function is used to pop or remove the last character in a string.

Example:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string name;
    cout << "Enter you full name: " ;
    getline(cin, name);

    /* delete last character */
    name.pop_back();

    cout << "Your full name is: " << name << endl;
    return 0;
}

Output:

Enter your full name: Foo Barr
Your full name is: Foo Bar

Size Manipulation

1. length()

This function returns the number of bytes/characters in a string.

Example:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string str = "words and lines";
    cout << "string: " << str << endl;
    
    /* print number of bytes */
    cout << "length of string: " << str.length() << endl;

    return 0;
}

Output:

string: words and lines
length of the string: 15

2. capacity()

This function returns the number of bytes allocated in memory for a string. This is different from the size of a string, where a string might have 100 bytes of allocated memory but contain only 10 characters.

Example:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    /* allocate 100 bytes for string str */
    string str(100, 'x');

    /* write text in the allocated space */
    str = "words and lines";

    cout << "string: " << str << endl;
    cout << "length of string: " << str.length() << endl;
    cout << "memory allocated to string: " << str.capacity() << endl;

    return 0;
}

Output:

string: words and lines
length of the string: 15
memory allocated to a string: 100

3. resize()

This function allows you to instantly change the number of characters in a string.

Example:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string str = "words and lines";
    cout << "Original string: " << str << endl;

    /* resize string */
    str.resize(5);
    cout << "Resized string: " << str << endl;

    return 0;
}

Output:

Original string: words and lines
Resized string: words

4. shrink_to_fit()

This function allows you to change the capacity of a string to fit its length.

Example:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string str(100, 'x');
    str = "words and lines";

    cout << "string: " << str << endl;
    cout << "length of string: " << str.length() << endl;
    cout << "capacity of string before shrinking: " << str.capacity() << endl;

    /* shrink string to fit its length */
    str.shrink_to_fit();
    cout << "capacity of string after shrinking: " << str.capacity() << endl;

    return 0;
}

Output:

string: words and lines
length of the string: 15
the capacity of the string before shrinking: 100
the capacity of the string after shrinking: 15

Functions for Iteration

Iterator functions are used to point at the first or last byte in a string. In the following example, we will be using iterator functions to loop through strings and printing the character of its contents by character.

1. begin()

This function returns an iterator pointing to the beginning of a string.

2. end()

This function returns an iterator pointing to the end of a string.

Example:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string str = "words and lines";

    /* create iterator to point at begin */
    string :: iterator it_begin = str.begin();

    /* create iterator to point at end */
    string :: iterator it_end = str.end();

    /* loop form begin to end and print characters */
    for( string :: iterator it = it_begin; it != it_end; it++ )
    {
        cout << *it ;
    }

    cout << endl;

    return 0;
}

Output:

words and lines

3. rbegin()

This function returns a reverse iterator pointing to the end of a string.

4. rend()

This function returns a reverse iterator pointing to the end of a string.

Example:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string str = "words and lines";

    /* create reverse iterator to point at end */
    string :: reverse_iterator it_begin = str.rbegin();

    /* create reverse iterator to point at begin */
    string :: reverse_iterator it_end = str.rend();

    /* loop form begin to end and print characters */
    for( string :: reverse_iterator it = it_begin; it != it_end; it++ )
    {
        cout << *it ;
    }

    cout << endl;

    return 0;
}

Output:

senil dna sdrow

Working with Multiple Strings

1. copy()

In case you need to copy your string into a character array for some reason, pass it to a C function for example; the copy function helps you do so.
You need __3 arguments__: target char array, a number of bytes, and string start position.

Example:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string str = "words and lines";

    /* create char array of size 6 */
    char ch_array[6];

    /* add null terminator at the end of char array to avoid garbage values in printing */
    ch_array[5] = '\0';

    /* copy first 5 bytes of string to char array */
    str.copy(ch_array, 5, 0);
    cout << "char array, first 5 bytes: " << ch_array << endl;

    /* copy last 5 bytes of string to char array */
    str.copy(ch_array, 5, str.length()-5);
    cout << "char array, last 5 bytes: " << ch_array << endl;

    return 0;
}

Output:

char array, first 5 bytes: words
char array, last 5 bytes: lines

2. swap()

This function allows us to swap the contents of 2 strings without needing to use a third variable.

Example:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string str_1 = "words and lines";
    string str_2 = "lines and words";

    cout << "string 1 before swapping: " << str_1 << endl;
    cout << "string 2 before swapping: " << str_2 << endl << endl;

    /* swap the 2 strings */
    str_1.swap(str_2);

    cout << "string 1 after swapping: " << str_1 << endl;
    cout << "string 2 after swapping: " << str_2 << endl;

    return 0;
}

Output:

string 1 before swapping: words and lines
string 2 before swapping: lines and words

string 1 after swapping: lines and words
string 2 after swapping: words and lines

3. concatenate using append()

Concatenate the contents of 2 strings into 1 string using append function.

Example:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string str_1 = "words and ";
    string str_2 = "lines";

    cout << "string 1 before concatenation: " << str_1 << endl;
    cout << "string 2 before concatenation: " << str_2 << endl << endl;

    /* concatenate string 2 into string 1 */
    str_1.append(str_2);

    cout << "string after concatenation: " << str_1 << endl;

    return 0;
}

Output:

string 1 before concatenation: words and
string 2 before concatenation: lines

string after concatenation: words and lines

4. concatenate using + operator

Concatenate the contents of 2 strings into 1 string by adding them.

Example:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string str_1 = "words and ";
    string str_2 = "lines";

    cout << "string 1 before concatenation: " << str_1 << endl;
    cout << "string 2 before concatenation: " << str_2 << endl << endl;

    /* concatenate string 2 into string 1 */
    str_1 += str_2;

    cout << "string after concatenation: " << str_1 << endl;

    return 0;
}

Output:

string 1 before concatenation: words and
string 2 before concatenation: lines

string after concatenation: words and lines

Strings Based Problems

In this section, we will introduce famous string-based problems and how to approach and solve them.

1. Count uppercase, lowercase, special character, and numeric values in a string

To approach such a problem you need to know that each character has a special ASCII value that you can check. For example, uppercase letters range between 65 and 90; therefore you would know that any character that lies between is an upper case letter. Lucky for you, C++ already evaluates the character using its ASCII value if used with “<“, “>” or “=” operators.

Solution:

#include <iostream>
#include <string>

using namespace std;

void count_string(string str)
{
    /* create counters for uppercase and lowercase letters, special characters and numbers */
    int count_upper = 0;
    int count_lower = 0;
    int count_special = 0;
    int count_num = 0;

    /* loop through string */
    for(int i = 0; i < str.length(); i++) { /* check if current char is in upper case ASCII range */ if( str[i] >= 'A' && str[i] <= 'Z' ) { count_upper++; } /* check if current char is in lower case ASCII range */ else if ( str[i] >= 'a' && str[i] <= 'z' ) { count_lower++; } /* check if current char is in numeric values ASCII range */ else if ( str[i] >= '0' && str[i] <= '9')
        {
            count_num++;
        }
        /* otherwise, it is a special character */
        else
        {
            count_special++;
        }
    }

    cout << "Number of upper case letters: " << count_upper << endl;
    cout << "Number of numeric values    : " << count_num << endl;
    cout << "Number of lower case letters: " << count_lower << endl;
    cout << "Number of special characters: " << count_special << endl;
}

int main()
{
    string str = "A22bbb@@@@";
    cout << "Input string: " << str << endl << endl;

    count_string(str);

    return 0;
}

Output:

Input string: A22bbb@@@@

Number of upper case letters: 1
Number of numeric values : 2
Number of lower case letters: 3
Number of special characters: 4

2. Remove spaces from a string

All you can do is create a new string, loop through old string and append all characters to new string except for spaces.

Solution:

#include <iostream>
#include <string>

using namespace std;

void remove_spaces(string str)
{
    string new_str;

    /* loop through string */
    for(int i = 0; i < str.length(); i++)
    {
        /* check if current character is not a space */
        if( str[i] != ' ' )
        {
            /* in such case, append character to new string */
            new_str += str[i];
        }
    }

    cout << "Output string: " << new_str << endl;
}

int main()
{
    string str = "Intentionally Leaveing Spaces Between Words";
    cout << "Input string: " << str << endl;

    remove_spaces(str);

    return 0;
}

Output:

Input string: Intentionally Leaving Spaces Between Words
Output string: IntentionallyLeaveingSpacesBetweenWords

3. Count the number of words in a string

In this problem, we know that words are typically separated with spaces. Therefore, what you can do is loop through your string and count the separators.

For sure this is the simplest solution that will not work if words are separated from other separators.

Solution:

#include <iostream>
#include <string>

using namespace std;

void count_words(string str)
{
    /* create variable counter of type integer */
    int count = 0;

    /* loop through characters in string */
    for(int i = 0; i < str.length(); i++)
    {
        /* check if current char is a space */
        if ( str[i] == ' ' )
        {
            /* in such case, increment the counter */
            count++;
        }
    }

    /* increment the counter one last time for the last word */
    count++;

    cout << "Number of words: " << count << endl;
}

int main()
{
    string str = "one two three four";
    cout << "Input string: " << str << endl;

    count_words(str);

    return 0;
}

Output:

Input string: one two three four
Number of words: 4

4. Count the number of word occurrences in a string

  • loop through your string until you find a character that matches the first character in your word;
  • create a substring using the current index and the length of the word you are looking for;
  • increment your counter if the 2 strings are identical.

Here we will need to use a new function called __substr()__. Simply, this function creates a substring from a string using __2 arguments__, start index and length of the new string.

Solution:

#include <iostream>
#include <string>

using namespace std;

void count_presence(string str, string word)
{
    /* create word counter variable */
    int count = 0;

    /* create temporary word of type string for comparison with original word */
    string temp_word;

    /* loop through string */
    for(int i = 0; i < str.length(); i++)
    {
        /* if current char matches first char in the word */
        if ( str[i] == word[0] )
        {
            /* create a temporary string with the same word size */
            temp_word = str.substr(i, word.length() );

            /* check if the temporary word matches the original word */
            if ( temp_word == word )
            {
                /* increment your counter in such case */
                count++;
            }
        }
    }

    cout << "Number of occurrences: " << count << endl;
}

int main()
{
    string word = "in";
    string str = "coding in mind";
    cout << "Input string: " << str << endl;
    cout << "Word to count: " << word << endl << endl;

    count_presence(str, word);

    return 0;
}

Output:

Here the word __in__ has appeared 3 times in cod**in**g **in** m**in**d

Input string: coding in mind
Word to count: in

Number of occurrences: 3