In this example, we will show you how to reverse the string
#include <iostream>
using namespace std;
void reverseString(string str){
int n = str.length();
for(int i = n-1; i >= 0; i--){
cout <<str[i];
}
}
int main(){
string str = "oceanLabz";
reverseString(str);
// cout<<str;
return 0;
}
Output:
zbaLnaeco
Explanation:
Step1: reverseString
Function
void reverseString(string str){
int n = str.length();
for(int i = n-1; i >= 0; i--){
cout << str[i];
}
}
Function Breakdown:
- Input: It takes a string
str
as an argument. - String Length: The length of the string is stored in the variable
n
using thelength()
method. - Reversing the String: The
for
loop is intended to print the string characters in reverse order, starting from the last index. However, the loop starts fromn
, which is out of bounds because the indices of a string go from0
ton-1
. This will result in unexpected behavior (sometimes printing garbage values or causing errors).
Loop Fix:
- The last character of the string is at index
n - 1
. So, the loop should start fromn - 1
and run untili >= 0
.
Step2: main()
Function
int main(){
string str = "oceanLabz";
reverseString(str);
return 0;
}
In the main()
function:
- A string
str
is initialized with"oceanLabz"
. - The
reverseString(str)
function is called to print the reverse of the string. - The
cout<<str;
line is commented out, which would print the original string if uncommented.