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
stras an argument. - String Length: The length of the string is stored in the variable
nusing thelength()method. - Reversing the String: The
forloop 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 from0ton-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 - 1and run untili >= 0.
Step2: main() Function
int main(){
string str = "oceanLabz";
reverseString(str);
return 0;
}
In the main() function:
- A string
stris 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.
