×

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

A while loop or while statement repeats all code of its body as long as a specific condition is satisfied. The loop ends if or when the condition no longer met.

The syntax for the while loop:

The syntax for a while loop is given by:

while(condition)
                     { 
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;
   int index=0, length;
while(length=str.length())
    {
      ch = str[index];
      str[index] = str[length-1-index];
      str[length-1-index] = ch;
   index++;
}
  cout<<str;
}

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: ";
     int i = (strlen(str) - 1);
         while(i>=0){
           cout << str[i];
          i--;
        }
         return 0;
}

The output of the program:

tnioptavaj

Method 4: Using a first-to-last approach ‘WHILE-LOOP’

#include<iostream>
using namespace std;
 // Function to reverse a string //
void reverseStr(string& str)
{
    int n = str.length();
    int j;
    // Swap character starting from two corners //
int i=0; 
   while(i<j) {
             int j=n-1;
          while(j<n){
             swap(str[i], str[j]); 
    j--; }
i++;}
}
 // 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

A while loop or while statement repeats all code of its body as long as a specific condition is satisfied. The loop ends if or when the condition no longer met.

The syntax for the while loop:

The syntax for a while loop is given by:

while(condition)
                     { 
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");
  1. 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;
   int index=0, length;
while(length=str.length())
    {
      ch = str[index];
      str[index] = str[length-1-index];
      str[length-1-index] = ch;
   index++;
}
  cout<<str;
}

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: ";
     int i = (strlen(str) - 1);
         while(i>=0){
           cout << str[i];
          i--;
        }
         return 0;
}

The output of the program:

tnioptavaj

Method 4: Using a first-to-last approach ‘WHILE-LOOP’

#include<iostream>
using namespace std;
 // Function to reverse a string //
void reverseStr(string& str)
{
    int n = str.length();
    int j;
    // Swap character starting from two corners //
int i=0; 
   while(i<j) {
             int j=n-1;
          while(j<n){
             swap(str[i], str[j]); 
    j--; }
i++;}
}
 // 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

Function overloading in C++

Function overloading in C++ As we know that C++ works on the OOP Concepts, that are abstraction, encapsulation, and data hiding, it also uses the other important feature of OOP, which...

8 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.

Is it fine to write void main() or main() in C/C++?

In C programming language: The default function return type in the C programming language is "int," which implies that main() will always return an integer value. In C, the void main()...

3 minutes read.

Fast Input and Output in C++

In competitive programming, it's critical to read input as quickly as possible in order to save time. "Warning: Big I / O data, be aware of certain languages (but most...

3 minutes read.

How the value is passed in C++

Introduction: The call-by-value method of giving arguments to a function duplicates the real value of an argument into the formal parameter of the function. In this instance, modifications to the parameter...

5 minutes read.

Stack in C++

Stack: The stack is a very popular data structure. It is the form of data structure that follows a particular order called FIFO(First-In-First-Out). In simple words, a stack is an Abstract...

4 minutes read.

C++ Recursion Function

A programming method called recursion that uses a function to call itself to address lesser problems. The Fibonacci sequence, factorial computation, and tree traversal are just a few of the...

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.

Diamond Pattern in C++ using For Loop

For Loop: A for loop is a repetitive control structure that allows you to create a loop for executing a specific number of times. The syntax of for loop: In C++, a for...

5 minutes read.

C++ Features

C++ is a general-purpose programming language that evolved from the C language to include an object-oriented paradigm. It is a compiled and imperative language. Object-Oriented Programming Object-oriented programming language concepts: ClassObjectsEncapsulationPolymorphismInheritanceAbstraction Class: A Class...

4 minutes read.

Returning Multiple Values from a Function using Tuple and Pair in C++

We may come across many situations where after the driver code's execution is performed in a code block, the return should be either multiple values or a single value possibly...

4 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++ Inline function

A C++ function that extends in line when called is known as an inline function. It reduces function call overhead by having the compiler use the function code rather than...

4 minutes read.

Bitwise Operator vs Logical Operator

Bitwise Operator  Bitwise operators perform operations bit by bit on bits.The value is converted to abinary during operations like addition, subtraction, division, and so on. These operations are carried out at the...

3 minutes read.

Free vs delete() in C++

Free vs delete() in C++ In this section, we will learn about the free() function and also create a C ++ program of the delete operator. What is free() Function in C++? In...

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.

C++ storage classes

Storage Classes are used to characterize a variable's or function's characteristics. These characteristics include scope, visibility, and life-time, which allow us to track the presence of a variable over the...

5 minutes read.

Sliding Window Technique in C++

Sliding Window Technique or Window Sliding Technique is a computational technique that is mainly used to reduce the use of nested loop and replace it with a single loop. It...

4 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.

C++ Keywords

In this article, we will discuss keywords in C++ with their several features and functions. What are Keywords in C++? In C++, a keyword is a reserved word that has a predefined...

4 minutes read.