How to Reverse String in C++?

Use `std::reverse` from ``

`std::string s = “hello”;`

`std::reverse(s.begin(), s.end());`

Use a loop with two pointers

`std::string s = “hello”;`

`int i = 0, j = s.size() – 1;`

`while (i < j) { std::swap(s[i], s[j]); ++i; --j; }`

Use a new string and append characters from back to front

`std::string s = “hello”;`

`std::string rev;`

`for (int i = s.size() – 1; i >= 0; –i) rev += s[i];`

Use reverse iterators

`std::string s = “hello”;`

`std::string rev(s.rbegin(), s.rend());`

Use recursion

`void reverseStr(std::string& s, int l, int r) { if (l >= r) return; std::swap(s[l], s[r]); reverseStr(s, l + 1, r – 1); }`

Suggested for You

Trending Today