
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
- Related Articles
- Reverse a string in C#
- Reverse a String (Recursive) C++
- Using iterative function print the given number in reverse order in C language
- Print all subsequences of a string using Iterative Method in C++
- Count consonants in a string (Iterative and recursive methods) in C++
- First uppercase letter in a string (Iterative and Recursive) in C++
- String reverse vs reverse! function in Ruby
- Reverse a string in C/C++
- C# program to reverse a string
- Function to reverse a string JavaScript
- Java Program to Reverse a String
- Reverse String in Python
- Write program to reverse a String without using reverse() method in Java?
- Reverse Vowels of a String in Python
- Reverse Words in a String in C++

Advertisements