reverse string

#include <iostream>
#include <string>

void reverseString(std::string& str) {
    int left = 0;
    int right = str.length() - 1;
    while (left < right) {
        std::swap(str[left], str[right]);
        left++;
        right--;
    }
}

int main() {
    std::string input = "Hello, world!";
    std::cout << "Original string: " << input << std::endl;

    reverseString(input);

    std::cout << "Reversed string: " << input << std::endl;

    return 0;
}
  1. Include Libraries: The code includes necessary libraries: <iostream> for input/output operations and <string> for string manipulation.

  2. reverseString Function: Defines a function reverseString that takes a reference to a string (std::string& str) as its parameter.

  3. Initialize Pointers: Initializes two variables, left and right, representing the leftmost and rightmost indices of the string respectively.

  4. Reverse Using Swap: Enters a while loop that continues until left becomes greater than or equal to right. Inside the loop, it swaps the characters at the left and right indices using std::swap.

  5. Increment/Decrement Pointers: Increments the left pointer and decrements the right pointer after each swap.

  6. main Function: Defines the main function where the program execution begins.

  7. Declare and Initialize String: Declares a string variable named input and assigns it the value "Hello, world!".

  8. Output Original String: Prints the original string ("Hello, world!") using std::cout.

  9. Call reverseString Function: Calls the reverseString function, passing the input string as an argument to reverse its content.

  10. Output Reversed String: Prints the reversed string using std::cout.

  11. Return Statement: Ends the main function with a return 0, indicating successful program execution.