How to Reverse a String in C++?

Use `std::reverse` from ``

Example: `std::string s = “hello”; std::reverse(s.begin(), s.end());`

Use a manual two-pointer swap approach

Example: `for (int i = 0, j = s.size() – 1; i < j; ++i, --j) std::swap(s[i], s[j]);`

Use a reverse loop to build a new string

Example: `std::string r; for (int i = s.size() – 1; i >= 0; –i) r += s[i];`

Use reverse iterators

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

Use `std::string` constructor with reverse iterators

Example: `std::string reversed(original.rbegin(), original.rend());`

Suggested for You

Trending Today