- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Reverse a String (Iterative) C++
There are many ways defined to reverse a string in the C++ code including stack, In-place, and iteration. In this sample, a simple string will be reversed iteratively with the following algorithm;
Algorithm
START Step-1: Input the string Step-2: Get the length of the string using length() method Step-3: Swap the last character to first using for loop Step-4: Print END
Incompatibility of the above calculation, the accompanying code in c++ language tried as following;
Example
#include <bits/stdc++.h> using namespace std; void strReverse(string& str){ int n = str.length(); // Swap character starting from two cout<<"interative reverse (Tomhanks)::"; for (int i = 0; i < n / 2; i++) swap(str[i], str[n - i - 1]); } int main(){ string str = "Tomhanks"; strReverse(str); cout << str; return 0; }
Output
As the above code compiled, the given string “Tomhanks” will be printed in reverse order as follows;
Iterative reverse (Tomhanks):: sknahmoT
Advertisements