C++ - String

This post will give an intorduction to c++ string and its essential functions.

In C++, we use the class std::string to store a sequence of characters, where we can perform various member functions and operators on the characters.

To use the std::string class mentioned above, simply include its header at the top of your .cpp file. (Note that the third line allows us to use identifiers in the std namespace without using the prefix std::)

#include <iostream>
#include <string>
using namespace std;

Normally, we would initialize a string variable in the following way:

int main() {
    string s1 = "abcd";
    string s2 = "efgh";
}

However, we could take advantage of the constructor of the string class for more flexibility. Later on as we explore some common string member functions, we will also find out that we can pass arguments to them the way we pass arguments to the constructor.  

Constructor

string()

This is the default constructor, which will construct an empty string of zero length. There are 2 ways to do this:

int main() {
    string s1 = string(); 
    string s2;   

    cout << "s1: " << s1 << endl;
    cout << "s2: " << s2 << endl;
}

  Output

s1: 
s2: 

 

string(const string& str)

This is the copy constructor, which will construct a copy of str

int main() {
    string s1 = "Hello"; 
    string s2 (s1);   

    cout << "s1: " << s1 << endl;
    cout << "s2: " << s2 << endl;
}

  Output

s1: Hello
s2: Hello

 

string(const string& str, size_t pos, size_t len = npos)

This is the copy constructor, which will construct a copy the portion of str that begins at the character position pos and spans len characters. If no len is provided, the substr starting from pos til the end of the string will be copied.

int main() {
    string s1 = "Hello"; 
    string s2 (s1, 0, 2);   
    string s3 (s1, 1);

    cout << "s1: " << s1 << endl;
    cout << "s2: " << s2 << endl;
    cout << "s3: " << s3 << endl;
}

  Output

s1: Hello
s2: He
s3: ello

 

string(size_t n, char c)

This is the fill constructor, which will fill the string with n copies of c. You can provide an alphabetical character or the ASCII code of a character.

int main() {
    string s1 (5, 'A');   
    string s2 (5, 122); 

    cout << "s1: " << s1 << endl;
    cout << "s2: " << s2 << endl;
}

  Output

s1: AAAAA
s2: zzzzz

 

string(iterator first, iterator last)

This is the range constructor, which will copy the sequence of characters in the range [first, last)

int main() {
    string s1 = "Hello, World";
    string s2 (s1.begin(), s1.begin()+8); 
    string s2 (s1.rbegin(), s1.rend()); 

    cout << "s1: " << s1 << endl;
    cout << "s2: " << s2 << endl;
    cout << "s3: " << s3 << endl;
}

  Output

s1: Hello, World
s2: Hello, W
s3: dlroW ,olleH

   

Iterator Functions

begin(), end()

begin(): Returns an iterator pointing to the first character of the string.  
end(): Returns an iterator pointing to the past-the-end character of the string.
Again, it should be noted that if we pass in iterators as arguments, they will be passed in the range [first, last). This means that the character pointed by the last iterator is not included.

s

int main() {
    string s1 = "Hello";
    for (auto it=s1.begin(); it!=s1.end(); ++it) {
        cout << *it;
    }
    cout << endl;
}

  Output

s1: Hello

 

rbegin(), rend()

rbegin():

  1. Returns a reverse iterator pointing to the last character of the string.
  2. Reverse iterators iterate backwards: incrementing them moves them towards begin().
  3. rbegin points to the character right before end().

rend():

  1. Returns a reverse iterator pointing to the theoretical element preceding the first character of the string.
string s1 = "Hello";
    for (auto it=s1.rbegin(); it!=s1.rend(); ++it) {
        cout << *it;
    }
    cout << endl;

  Output

s1: olleH

   

Now we will have a quick glance at some other commonly used string functions

Capacity member functions

size(), length()

Both functions are identical and return the length of the string.

int main() {
    string s1 = "Hello";
    cout << "s1.length(): " << s1.length() << endl;
    cout << "s1.size(): " << s1.size() << endl;
}

  Output

s1.length(): 5
s1.size(): 5

 

clear()

Delete the contents of the string, turning it into an empty string.

    string s1 = "Hello";
    cout << "s1: " << s1 << endl;
    s1.clear();
    cout << "s1: " << s1 << endl;

  Output

s1: Hello
s1: 

 

empty()

Returns whether the string is empty. Return Value

  1. true if string length is 0
  2. false otherwise
    string s1 = "Hello";
    string s2 = "";
    cout << "s1.empty(): " << s1.empty() << endl;
    cout << "s2.empty(): " << s2.empty() << endl;

  Output

s1.empty(): 0
s2.empty(): 1

   

Element access member functions

back(), front()

Returns a reference to the first/last character

    string s1 = "Hello";
    cout << "s1.front(): " << s1.front() << endl;
    s1.front() = 'h';
    cout << "s1.front(): " << s1.front() << endl;
    cout << "s1.back(): " << s1.back() << endl;
    s1.back() = 'O';
    cout << "s1.back(): " << s1.back() << endl;

  Output

s1.front(): H
s1.front(): h
s1.back(): o
s1.back(): O

   

Modifier member functions

+ operator

Append a string to the end of another.

    string s1 = "Hello";
    string s2 = ", ";
    string s3 = "World.";
    string s4 = "Hi. ";

    cout << "s1: " << s1 << endl;
    s1 += s2;
    s1 += s3;
    cout << "s1: " << s1 << endl;
    s1 = s4 + s1;
    cout << "s1: " << s1 << endl;

  Output

s1: Hello
s1: Hello, World.
s1: Hi. Hello, World.

 

append()

Similar to ‘+’ operator, append() appends characters to the end of a string. However, similar to the constructor, we can pass in various type of argument as the parameters.

    string s1 = "Hello";
    string s2 = ", ";
    string s3 = "World.";

    s1.append(s2);
    s1.append(s3, 0, 5); // 0 = starting position of s3 to append, 5 = length of string to append
    s1.append(5, '.');
    s1.append(s2, 1, 1); 
    s1.append(s1.begin()+1, s1.begin()+5);

    cout << "s1: " << s1 << endl;

  Output

s1: Hello, World..... ello

 

insert()

The insert() function has the same functionality as the append() function but we can choose insert to anywhere in the string. There are 2 different ways we can do this. Say we are trying to insert str to a string s.

  1. s.insert(startingPosition, str, startingPosOfStr, lengthOfSubstr). startingPosition indicates the insertion point of the new contents to s, which will be inserted before the character at startingPosition. startingPosOfStr indicates the position of the first character in str to be inserted to s. lengthOfSubstr indicates the length of the substring to be inserted to s, starting from index startingPosOfStr. If the last 2 parameters are no provided, the entire str will be inserted to startingPosition;.
  2. s.insert(startingPosition, beginningIterator, endIterator). This will insert the if str in the range [beginningIterator, endIterator)
    string s1 = "abef";
    string s2 = "cd";
    string s3 = "zghijz";

    cout << "s1: " << s1 << endl;
    s1.insert(2, s2); // 2 = we insert s2 at index 2 of s1
    cout << "s1: " << s1 << endl;
    s1.insert(5, s3, 1, 4); // The substr that we are inserting will start from index 1 and has length 4
    cout << "s1: " << s1 << endl;
    s1.insert(s1.end(), s3.begin(), s3.begin()+1); // .end() = we insert at the end of s1
    cout << "s1: " << s1 << endl;

  Output

s1: abef
s1: abcdef
s1: abcdeghijf
s1: abcdeghijfz

 

erase()

Erase a part of the string or even the entire string. Similar to insert(), there are 2 ways we can do this. Say we are trying to delete from the string s:

  1. s.erase(startingPos = 0, length). This will erase the portion of the string starting at startingPos and spans length.
  2. s.erase(beginningIterator, endIterator). This will erase the portion of the string in the range [beginningIterator, endIterator)
    string s1 = "Hello, World";

    cout << "s1: " << s1 << endl;
    s1.erase(5, 2); // 5 = starting position of s1 to erase, 2 = length of string to erase
    cout << "s1: " << s1 << endl; 
    s1.erase(s1.begin()+5); // Removes the character pointed by the iterator s1.begin()+5
    cout << "s1: " << s1 << endl; 
    s1.erase(s1.begin()+1, s1.begin()+8);
    cout << "s1: " << s1 << endl; 

  Output

s1: Hello, World
s1: HelloWorld
s1: Helloorld
s1: Hd

 

push_back(), pop_back()

Append/remove a character from the end of a string.

    string s1 = "H";

    cout << "s1: " << s1 << endl;
    s1.push_back('e');
    s1.push_back('l');
    s1.push_back('l');
    s1.push_back('l');
    cout << "s1: " << s1 << endl;
    s1.pop_back();
    s1.pop_back();
    s1.pop_back();
    s1.pop_back();
    cout << "s1: " << s1 << endl;

  Output

s1: H
s1: Helll
s1: H

   

String Operations

find()

find() will return the position of the first occurrence of the content passed as the arguments. find() takes in 2 parameters, str/c and pos. str/c means that we can search for a string or character while pos means we will only start searching from that index. If pos is not passed as an argument, its default value will be 0. The return value is of type size_t, which is an unsigned integer type. We can just think of it as an int type. If we fail to find str/c, find() will return npos which is equivalent to the largest value of size_t.

 

    string s1 = "Hello, World. Goodbye, World";
    cout << "World in s1: " << s1.find("World") << endl; // "World" first appeared at index 7
    cout << "Hello in s1: " << s1.find("Hello") << endl;
    cout << "Person in s1: " << s1.find("Person") << endl;

  Output:

World in s1: 7
Hello in s1: 0
Person in s1: 18446744073709551615

 

substr()

This function will return a new string object that has its value initialized to a copy of the substring of the original string object. This function takes in 2 parameters: pos and len. pos indicates the index of the first character to be copied. len indicates the length of the substring to be copied. If we don’t pass in the len argument, substr() will return a string object that copies the original string from pos all the way to the ennd.

 

    string s1 = "Hello, World. Goodbye, World";
    string s2 = s1.substr(7, 5);
    cout << s2 << endl;
    size_t pos = s1.find('G');
    string s3 = s1.substr(pos); // Creates a substring that starts from 'G' in s1
    cout << s3 << endl;

  Output

World
Goodbye, World

Reference

  1. cplusplus 2022, std::string::string, cplusplus, viewed 11 December 2022,

    https://cplusplus.com/reference/string/string/