C++

C++ String Reverse

If the string, “vwxyz“, is reproduced in the new order as, “zyxwv“.

Then the string has been reversed. Unfortunately, such direct reversibility is not possible in C++. However, there is a classical workaround for reversing a string in C++. Keep reading this article to know-how.

A string can be created in two main ways in C++. A string can be created as a constant pointer to a sequence of characters. A string can also be created by instantiating a string object from the string class. This article deals with string objects instantiated from the string class. This means the string library has to be included in order to execute the code samples in this article.

A string object is a data structure where the string literal is a list. Each character is of one element in the list. And so, a literal string can be handled like an array of elements.

This article explains the classical workaround to reverse a string in C++. This essentially iterates the string literal, backward. Having a summary knowledge of forward iteration enables the reader to understand reverse iteration better. This article deals with string objects instantiated from the string class.

All the string code for this tutorial is written in the C++ main() function unless otherwise indicated.

Article Content

  1. String Forward Iteration
  2. String Reverse Iteration
  3. String Constant Reverse Iteration
  4. Conclusion

Forward Iteration

An iterator is a pointer class from which iterator objects can be instantiated. An iterator object can be used to scan string elements from the beginning of the string list to the end of the string list. The string member function, begin(), returns an iterator that points to the first element of the string literal. It can be incremented until it reaches, just after the last element of the string. The string member function, end(), returns an iterator that points just after the last element of the string literal. It can be decremented until it will reach, the last element of the string. These two iterators are considered as forward iterators, though the second one iterates backward.

For a string object with the variable name, str, the following statement will return a begin iterator:

string::iterator p = str.begin();

Here, p is a begin iterator. An end iterator can be returned by the following statement:

string::iterator q = str.end();

Here, q is an end iterator. p and q above are of the same type and can even be interchanged.

The following code prints out all the characters of the string, from the start to the end:

string str = {'v', 'w', 'x', 'y', 'z', '\0'};

for (string::iterator p = str.begin(); p != str.end(); p++) {

    cout << *p << ' ';

}

cout << endl;

The output is:

v w x y z

‘\0’ should not be printed. It is supposed to be there to mark the end of the string literal. Note how the begin iterator was obtained. The iteration scans the sting list from the beginning to the end, comparing the iterator of each element with that returned by str.begin(); after incrementing. When the returned iterator is the one just after the last element, iterating stops. An iterator is incremented or decremented in the same way that an index is. The expression, *p returns the value pointed to, by the iterator, p.

The following code prints out the values in the string, from the last character to the first character, using the end iterator:

string str = "vwxyz";

 

string::iterator q = str.end();

for (q = --q; q >= str.begin(); q--) {

    cout << *q << ' ';

}

cout << endl;

The output is:

z y x w v

This is an indirect reversal of a string. The end iterator points just after the end of the string literal, and such a point is not an element. In order for it to point to the last element, it has to be decremented. From there, the iteration can go backward.

Because of that, the end iterator was declared outside the for-loop. The initial value of the iterator in the for-loop is a single decrement. The iterator is decremented in steps until it reaches the first element as indicated by “str.begin()”. This is an informal way to iterate backward. That is, this is an informal way to reverse a vector (indirectly).

Changing Character of an Element

The string object is a data structure, where the string literal is of a list. The list consists of elements. Each element has a character, and that character is the value of the element. The characters are also values of the string. The complete string literal is the value of the string object.

When the declaration of the string object is not preceded by const (for constant), the value of any element in the string can be changed. Illustration:

string str = "vwxyz";

 

string::iterator q = str.end();

q--; q--; q--;

 

*q = 'a';

string::iterator B = str.end();

for (B = --B; B >= str.begin(); B--) {

    cout << *B << ' ';

}

cout << endl;

The output is:

z y a w v

q–; q–; q–;” decremented the end iterator 3 times to point to ‘C’.

When the string object declaration is preceded by const, the characters are read-only. For such code, the iterator returned has to be const_iterator. In this case, the code does not compile. The following code will issue an error message:

const string str = "vwxyz";

 

string::const_iterator q = str.end();

q--; q--; q--;

 

*q = 'a';

Reverse Iteration

The iterator used with reverse iteration is reverse_iterator. Another member function of the string class is, rend(), which returns an iterator that points just in front of the first element of the string object. Still, another member function of the string class is rbegin(), which returns an iterator that points to the last element of the string object. The following code illustrates the use of the returned reverse_iterator, reading in the forward direction, from the first element to the last element:

string str = "vwxyz";

string::reverse_iterator p = str.rend();

 

for (p = --p; p >= str.rbegin(); p--) {

    cout << *p << ' ';

}

cout << endl;

The output is:

v w x y z

Notice that with the reverse_iterator, ++ is — and <= is >= , in the while condition.

The following code iterates backward, using the iterator of rbegin():

string str = "vwxyz";

for (string::reverse_iterator q = str.rbegin(); q <= str.rend(); q++) {

    cout << *q << ' ';

}

cout << endl;

The output is:

z y x w v 

Again, ++ is used instead of — , and <= is used instead of >= .

Changing Character of an Element

When the declaration of the string object is not preceded by const (for constant), the value of any element in the string can be changed. Illustration:

string str = "vwxyz";

 

string::reverse_iterator q = str.rbegin();

q++; q++;

 

*q = 'a';

 

for (string::reverse_iterator B = str.rbegin(); B <= str.rend(); B++) {

    cout << *B << ' ';

}

cout << endl;

The output is:

z y a w v

The rbegin() iterator, q, is decremented two times with “q++; q++;” to point at ‘C’, since it initially points to the last element.

If a string object is preceded with const, then non of the characters can be changed with any kind of iterator. The compiler will issue an error message for the following code because the code tries to modify the value of ‘C’:

const string str = "vwxyz";

 

string::const_reverse_iterator q = str.rbegin();

q++; q++;

 

*q = 'a';

String Constant Reverse Iteration

A const_reverse_iterator is returned by the member function, crbegin(). crbegin() is like rbegin(), but the value pointed to by its iterator cannot be changed. A const_reverse_iterator is also returned by another member function, crend(). crend() is like rend(), but the value pointed to, by its iterator, cannot be changed.

The following code displays all the values of the string object, using const_reverse_iterator, starting from the last element:

const string str = "vwxyz";

 

for (string::const_reverse_iterator q = str.crbegin(); q <= str.crend(); q++) {

    cout << *q << ' ';

}

cout << endl;

The output is:

z y x w v 

Though the declaration of the string object is not preceded by const, the following code will not compile. This is because of the use of const_reverse_iterator. Even if the declaration was preceded by const, it would still not compile for the same reason. The code is:

const string str = "vwxyz";

 

string::const_reverse_iterator q = str.crbegin();

q++; q++;

 

*q = 'a';

Conclusion

The string class does not have a member function to reverse a string. However, a string can be reversed indirectly by iterating from back to front. The member functions involved are, end(), begin(), rend(), rbegin(), crend() and crbegin(). Iterators involved are iterator, reverse_iterator, and const_reverse_iterator. These features are combined to produce an indirect but still effective reversal of the literal of a string object.

About the author

Chrysanthus Forcha

Discoverer of mathematics Integration from First Principles and related series. Master’s Degree in Technical Education, specializing in Electronics and Computer Software. BSc Electronics. I also have knowledge and experience at the Master’s level in Computing and Telecommunications. Out of 20,000 writers, I was the 37th best writer at devarticles.com. I have been working in these fields for more than 10 years.