How to Reverse String in C++?


Write a method that reverses the given input string. Example: Given s = “12345”, return “54321”.

STL

The C++ STL provides the reverse method that does the job.

1
2
3
4
5
6
7
class Solution {
public:
    string reverseString(string s) {
        reverse(s.begin(), s.end());
        return s;
    }
};
class Solution {
public:
    string reverseString(string s) {
        reverse(s.begin(), s.end());
        return s;
    }
};

The string constructor takes the iterator so we can use rbegin() and rend() in which the ‘r’ means reversed.

1
2
3
4
5
6
7
class Solution {
public:
    string reverseString(string s) {
        auto x = string(s.rbegin(), s.rend());
        return x;
    }
};
class Solution {
public:
    string reverseString(string s) {
        auto x = string(s.rbegin(), s.rend());
        return x;
    }
};

Two Pointers

We initialize two pointers, from the start and end respectively. Swap two characters until these pointers meet in the middle. O(n) complexity.

1
2
3
4
5
6
7
8
9
10
class Solution {
public:
    string reverseString(string s) {
        int i = 0, j = s.length() - 1;
        while (i < j) {
            swap(s[i++], s[j--]);
        }
        return s;
    }
};
class Solution {
public:
    string reverseString(string s) {
        int i = 0, j = s.length() - 1;
        while (i < j) {
            swap(s[i++], s[j--]);
        }
        return s;
    }
};

Make a Copy

If we make a copy, we can re-assign the reverse characters easily. O(n) complexity.

1
2
3
4
5
6
7
8
9
10
class Solution {
public:
    string reverseString(string s) {
        string x = s;
        for (int i = 0; i < s.length(); i ++) {
            x[i] = s[s.length() - i - 1];
        }
        return x;
    }
};
class Solution {
public:
    string reverseString(string s) {
        string x = s;
        for (int i = 0; i < s.length(); i ++) {
            x[i] = s[s.length() - i - 1];
        }
        return x;
    }
};

Add Character Reverse

Another way is to add character in the reverse order.

1
2
3
4
5
6
7
8
9
10
class Solution {
public:
    string reverseString(string s) {
        string x = "";
        for (int i = 0; i < s.length(); i ++) {
            x = s[i] + x;
        }
        return x;
    }
};
class Solution {
public:
    string reverseString(string s) {
        string x = "";
        for (int i = 0; i < s.length(); i ++) {
            x = s[i] + x;
        }
        return x;
    }
};

See also: Reverse a Sentence (Sentence Reversal Algorithm)

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
319 words
Last Post: Last Minute Tips before Phone Interview
Next Post: Dynamic Programming - Integer Break

The Permanent URL is: How to Reverse String in C++?

Leave a Reply