×

How to Reverse a String in C++ using For Loop

For Loop:

We may loop through a certain section of C++ code repeatedly using the for loop.

A for loop is carried out if the test expression yields a true result. The loop comes to an end when the test expression returns false. This suggests that each time when the loop is iterated, the condition must be verified before the execution of body. If the evaluation returns a true result, the body of the loop is executed. If the evaluation yields a false result, the loop's body will not run.

The syntax of for loop:

In C++, a for loop is written as:

for (initialize; condition; increment) 
 {
 statement(x);
}

Strings:

In C++, a string is an object that represents a group (or sequence) of various characters. Strings are part of the standard string class in C++ (std::string).

The characters of a string are stored as a collection of bytes in contiguous memory regions by the string class. Strings are most typically employed in programs that need text manipulation. In C++, we may operate a variety of operations on strings. For instance, reversing, concatenating, or sending a function as an argument.

Syntax:

The syntax for generating a string in C++ is simple. In C++, the string keyword is used to generate a string. Before we can use this keyword, we must first include the standard string class in our program.

string str_ name = "this is C++ string";

Example of Declare and Initialize string:

string str_ name = "hello";

                 (or)

string str_ name("hello");
  • C++ also supports C-style strings.

Syntax:

Char str_name[  ];

String reverse using for loop:

The reverse of a string can be done using different ways:

Method 1:

C++ string reverse using reverse ()

  • reverse () is a function in the algorithm header file that reverses a sequence within a defined range. We use the reverse () function and include the <algorithm> header file.

Program to print reverse of string using REVERSE ()

#include <iostream> 
#include <algorithm>  
using namespace std;
 int main()
 {
   string str = "Java-TPoint";
   reverse(str.begin(), str.end());
   cout << str << endl;
}

The output of the program:

tnioPT-avaJ

Method 2: C++ String Reverse by Swapping Characters:

Algorithm:

Step 1: Start.

Step 2: Take a string and store it in the variable str.

Step 3: Initialize variable index with 0.

Step 4: Check to see if the index is less than half of the str's length. If its not true, go to step 7.

Step 5: Str[index] should be swapped by str[str length - 1 - index].

Step 6: Increment index, go to step 4.

Step 7: Stop.

Program to print the reverse of a string by swapping characters:

#include <iostream> 
using namespace std;
 int main() 
{
   string str = "Java-TPoint";
   char ch;
   for (int index = 0, lenth= str.length(); index< lenth/2; index++)  
   {
      ch = str[index];
      str[index] = str[lenth-1-index];
      str[lenth-1-index] = ch;
   }
  cout << str << endl;
}

The output of the program:

tnioPT-avaJ

Method 3:

This method includes the two pointers, one at the beginning and the other at the end of the sequence. The characters are reversed one by one with the help of these pointers.

Program to print reverse of string:

#include <iostream>
#include <string.h>
using namespace std;
int main()
{
    char str[] = "javatpoint";
    cout << "Original string: " << str;
     cout << endl << "String after reverse: ";
     for(int i = (strlen(str) - 1); i >= 0; i--)
         {
           cout << str[i];
        }
         return 0;
}

The output of the program:

tnioptavaj

Method 4: Using a first-to-last approach ‘for’ loop

#include <iostream >
using namespace std;
 // Function to reverse a string //
void reverseStr(string& str)
{
    int n = str.length();
    // Swap character starting from two corners //
    for (int i=0, j=n-1; i<j; i++,j--) 
    {
        swap(str[i], str[j]); 
     }
}
 // main program //
int main()
{
    string str = "javatpoint";
    reverseStr(str);
    cout << str;
    return 0;
}

Output:

tnioptavaj

Method 5: C++ String Reverse using Recursion:

Recursion: In C++, recursion is a method that calls itself, either directly or indirectly, until a certain condition is met. This technique has a base case and a recursive condition. It continuously calls the function within the same function. The recursive condition aids in the repeated execution of code, whereas the base case aids in the condition's termination.

If the recursive function does not have a base case, the recursive function will continue to repeat itself indefinitely.

Program:

#include <iostream>
using namespace std;
 void strreverse(string& str, int n, int i)
{
   if (n <= i)
   {
      return;
   }
   swap(str[i], str[n]);
   strreverse(str, n - 1, i + 1);
}
  int main()
 {
   string str = "javatpoint";
   strreverse(str, str.length() - 1, 0);
   cout << str << endl;
}

Output:

tnioptavaj

Related Topics

Passing a Vector to a function in C++

A pointer is sent to the function when we feed it an array. However, there are two ways to pass a vector: Pass by Value Pass by Reference A copy of a vector...

3 minutes read.

Naming Convention in C++

The first and most fundamental step a programmer takes to produce clean code is to name a file or a variable. This naming must be acceptable so that it serves...

5 minutes read.

Scope Resolution Operator in C++

The scope resolution operator and its different usage in the C++ programming language will be discussed in this section. The scope resolution operator is used to refer to an out-of-scope...

6 minutes read.

Size_t Data Type in C++

In C++, the type to express the object size in bytes is defined as Size_t, an unsigned integer type offered by the standard library for describing the object's size and...

3 minutes read.

Skyline Problem in C++

We have given n rectangular buildings in a 2-dimensional city. Here, to compute the Skyline of the given n rectangle structures in a two-dimensional metropolis while removing hidden lines, the...

3 minutes read.

Divide by Zero Exception in C++

We use exception handling method to handle the divide by zero exception. Dividing a number with zero is generally mathematical error. We have to exception handling method to overcome this...

2 minutes read.

C++ STL Components

C++ STL Components In today’s article, we are going to learn about all the points things that is related to STL in C++ so stay connected because you are going to...

6 minutes read.

C++ Signal Handling

Signals are interruptions sent by the operating system to a process to cause it to cease doing its current job and focus on the task for which the interrupt was...

4 minutes read.

C++ Nested if

C++'s nested if statements enable more complex decision-making when a section of code needs to execute only after a set of conditions is met. The nested if control statement refers...

4 minutes read.

C++ cin and cout

In this article, we will discuss the C++ cin and cout with their library and examples. C++ Standard Input/Output: User-program communication is made possible by C++’s usage of input and output (I/O)...

5 minutes read.

Implementing the sets without C++ STL containers

Many practical features and tools in C++ support us in programming competitions. One of these parts is a set from the Standard Template Library (STL), which offers an effective way...

6 minutes read.

System() function in C++

As a part of the c/c+ standard library, the system() function passes commands to be executed by the operating system’s command processor or terminal and returns the completed command. We...

2 minutes read.

C++ Type Casting

The type casting of variables in the C++ programming language will be covered in this section. The term "type casting" describes how software converts one data type to another. There...

9 minutes read.

Difference between OOP and POP in C++

Object-Oriented Programming (OOP) Prioritizes data over methods (functions) and treats data as an essential component of program development.  OOP prohibits the free flow of data throughout the system. Tighter ties to data manipulation...

4 minutes read.

C++ Continue

In C++, the continue statement is a useful tool for avoiding specific scenarios without breaking the loop. It is employed inside loops to move directly to the following iteration and...

4 minutes read.

Single level Inheritance

Inheritance is a fundamental element of C++’s Object-Oriented Programming (OOP). It allows a class (called the derived class) to inherit characteristics and attributes from another class (called the base class)....

5 minutes read.

External merge sort in C++

External merge sort in C++ External sorting is a concept for a group of sorting algorithms capable of handling large data volumes. External sorting is needed if the information getting sorted...

9 minutes read.

Pointer to Object in C++

What is a pointer? A pointer in C++ is used to point the variable by storing the address of the variable. In C++, to print the address of the variable, we...

4 minutes read.

rand() and srand() in C / C++

In this tutorial, we'll explore the syntax, usage, and examples of the C++ STL functions rand() and srand(). What exactly is rand()? The C++ STL's built-in rand() function is defined in the...

3 minutes read.

How is multiset implemented in C++

Similar to sets, multisets are an associative container type where several items may share the same values. Associative containers implement instantly searchable sorted data structures with O(log n) complexity. In a multiset,...

5 minutes read.