Complete the code to reverse a string using the built-in reverse function.
#include <algorithm> #include <string> #include <iostream> int main() { std::string s = "hello"; std::reverse(s.[1](), s.end()); std::cout << s << std::endl; return 0; }
The std::reverse function requires iterators to the beginning and end of the string. The correct method to get the start iterator is begin().
Complete the code to reverse a string by swapping characters using a loop.
#include <algorithm> #include <string> #include <iostream> int main() { std::string s = "world"; int n = s.size(); for (int i = 0; i < n / 2; ++i) { std::swap(s[i], s[[1]]); } std::cout << s << std::endl; return 0; }
To swap characters from start and end, the index from the end is n - i - 1.
Fix the error in the code that attempts to reverse a string using a while loop.
#include <string> #include <iostream> int main() { std::string s = "example"; int left = 0; int right = s.size() - 1; while (left < right) { char temp = s[left]; s[left] = s[[1]]; s[right] = temp; ++left; --right; } std::cout << s << std::endl; return 0; }
s[left] to itself causing no change.left + 1 or right - 1 which skips characters.To swap characters correctly, s[left] should be assigned s[right].
Fill both blanks to create a reversed copy of a string using a for loop.
#include <string> #include <iostream> int main() { std::string s = "reverse"; std::string rev = ""; for (int i = s.size() - 1; i >= 0; [1]) { rev.[2](s[i]); } std::cout << rev << std::endl; return 0; }
++i which causes an infinite loop.append which expects a string, not a single char.The loop index should decrease with --i to move backward. The method push_back adds a character to the end of the string.
Fill the blanks to create a reversed string using a range-based for loop and prepending characters.
#include <string> #include <iostream> int main() { std::string s = "loop"; std::string rev = ""; for (char c : s) { rev = [1] + [2]; } std::cout << rev << std::endl; return 0; }
To reverse by prepending, assign rev = c + rev. This adds the current character before the existing string.
