×

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

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[  ];

Do-While Loop:

An iterative loop that checks the condition at the end. The Do-While loop can be used whenever a test condition is certain, as it enters the loop at once and then checks if the given condition is true or false. The loop actions or statements will be repeated indefinitely as long as the test requirements are met

Note: DO-WHILE LOOP means “first loop execute, then condition check”.

SYNTAX:

The Syntax of the DO-WHILE loop is:

Do
           { 
            statement(s);
           } 
         while(expression);

String reverse using a do-while 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 

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

The output of the program:

tnioptavaj

Method 4: Using a first-to-last approach ‘DO-WHILE 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 //
     int i=0; 
     int j=n-1;  
    do{
        swap(str[i], str[j]);
       i++;
       j--; 
     }while(i<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

Bit Manipulation in C++

The high-level language in which we communicate is not understood by the computer. As a result, there existed a standard mechanism for understanding any instruction sent to the computer. At...

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

4-Dimensional Array in C/C++

A four-dimensional (4D) array is an array of three-dimensional (3D) arrays, or in other words we can say that a 4- dimensional array is an array of arrays of arrays...

3 minutes read.

Converting string into integer in C++

When programming in C++, we'll frequently need to change one data type to another. When we use C++ to create apps, we must transform data from one type to another. When...

7 minutes read.

C++ For loop

C++ loop Statement C++ Loop statement allows us to repeat the execution of a statement or group of statements multiple times. The statement(s) repeat execution within loop until the condition of loop...

2 minutes read.

This keyword in C++

This keyword in C++ is a pointer which points to the object. It is passed as an argument to functions which helps in accessing the object. It is used for a...

3 minutes read.

Maps in C++

Maps: Maps in C++ are the containers associated with key and mapped values. By keys and mapped values, we mean that the maps are used to store elements formed by the...

4 minutes read.

Array of Object in C++

What is an Array? In C++, an array is a group of related data types, such as int, char, float, double, etc., that are easily accessed by index value alone and...

12 minutes read.

Armstrong number using for loop in C++

What is For Loop? A for loop is a repetitive control structure that allows you to create a loop to execute a specific number of times efficiently. The syntax that can be...

4 minutes read.

Bitmasking in C++

Bitmasking is a technique that is used to access a particular bit within the data bytes. When you apply the iterative approach, this phenomenon is used. A bitmask is described...

6 minutes read.

Decltype type Specifier in C++

The primary use of C++ decltype is to inspect the declaration type of an entity in an expression. The auto keyword can declare a particular type of variable, whereas the...

4 minutes read.

Data Hiding in C++

C++ : High-performance apps can be made using the cross-platform language C++. Bjarne Stroustrup created C++ as an addition to the C language. Programmers have extensive control over memory and system...

3 minutes read.

Reverse function in C++

The function std::reverse() is included in the standard template library of C++. It takes in a beginning and ending iterator, reversing the order. To use the reverse statement, we need...

2 minutes read.

Inheritance and Friendship in C++

In this tutorial, we will look into what Inheritance and Friendship in C++ are, as well as the differences between the two. What is Inheritance in C++: In C++, inheritance is an...

2 minutes read.

Structured Binding in C++

Structured binding is the new feature of C++ 17. It is used to bind the specified name with an element of the initializer. Structure binding is used to declare multiple...

3 minutes read.

Vector Size in C++

What are Vectors?  In the C++ programming language, vectors are run-time sequence containers representing arrays with variable sizes, which are contained within STL (Standard Template Library). They utilize contiguous storage spaces...

6 minutes read.

Dynamic Binding in C++

The notion of dynamic binding solved the challenges associated with static binding. Static binding refers to bindings that can be resolved by the compiler at runtime. All storage, stationary, and...

3 minutes read.

C++ Range-based For Loop

In C++ language, the range-based for loop was added, which is far superior than the ordinary For loop. The implementation of a range-based for loop doesn't really need much code. It's a...

4 minutes read.

Learn C++ Tutorial

C++ Introduction C++ is an object-oriented programming language. It was developed by Bjarne Stroustrup at AT&T Bell Laboratories. It is superset (extension) of C programming language. Depending upon features supported by programming...

10 minutes read.

std::distance() in C++

The primary function of std::distance is to facilitate the total number of elements if we have two iterators. It is defined inside the header files. It has both magnitude and...

2 minutes read.