c++ reverse string
#include <iostream>
#include <string>
void reverseString(std::string& str) {
int start = 0;
int end = str.length() - 1;
while (start < end) {
std::swap(str[start], str[end]);
start++;
end--;
}
}
int main() {
std::string myString = "Hello, World!";
std::cout << "Original string: " << myString << std::endl;
reverseString(myString);
std::cout << "Reversed string: " << myString << std::endl;
return 0;
}
Include necessary headers:
#include <iostream>
and#include <string>
.Define a function
reverseString
that takes a reference to astd::string
as a parameter.Inside the function, declare two integers,
start
andend
, and initialize them to the beginning and end indices of the string, respectively.Use a
while
loop to iterate until thestart
index is less than theend
index.Inside the loop, use
std::swap
to swap the characters at thestart
andend
indices.Increment the
start
index and decrement theend
index after the swap.In the
main
function, declare astd::string
variable namedmyString
and initialize it with the original string "Hello, World!".Print the original string using
std::cout
.Call the
reverseString
function, passingmyString
as an argument, to reverse the string.Print the reversed string using
std::cout
.Return 0 to indicate successful program execution.