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;
}
Include Libraries: The code includes necessary libraries:
<iostream>
for input/output operations and<string>
for string manipulation.reverseString
Function: Defines a functionreverseString
that takes a reference to a string (std::string& str
) as its parameter.Initialize Pointers: Initializes two variables,
left
andright
, representing the leftmost and rightmost indices of the string respectively.Reverse Using Swap: Enters a
while
loop that continues untilleft
becomes greater than or equal toright
. Inside the loop, it swaps the characters at theleft
andright
indices usingstd::swap
.Increment/Decrement Pointers: Increments the
left
pointer and decrements theright
pointer after each swap.main
Function: Defines themain
function where the program execution begins.Declare and Initialize String: Declares a string variable named
input
and assigns it the value"Hello, world!"
.Output Original String: Prints the original string (
"Hello, world!"
) usingstd::cout
.Call
reverseString
Function: Calls thereverseString
function, passing theinput
string as an argument to reverse its content.Output Reversed String: Prints the reversed string using
std::cout
.Return Statement: Ends the
main
function with areturn 0
, indicating successful program execution.