Custom function to reverse a string
First, letโs write a custom function to reverse a given string. This function will swap the first character with the last, then the second with the second-last, and so on until the entire string is reversed.
Create the reverseStr
function and pass the string by reference. This way, we can modify the original string rather than returning a new one. The function will have a for loop that will swap characters on either side of the string, gradually working its way inwards until the entire string is reversed.
#include<iostream>
#include<string>
using namespace std;
void reverseStr(string& str) {
int n = str.length();
for (int i = 0; i < n / 2; i++) {
swap(str[i], str[n - i - 1]);
}
}