×

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

Initialize Array of objects with parameterized constructors in C++

Initialize Array of objects with parameterized constructors in C++ When a class is defined, only the specification for the object is specified; no memory or capacity is allocated. You need to...

3 minutes read.

C++ Break

In this article, we will discuss the C++ Break statement with its syntax, algorithm, pseudocode, and examples. The C++ break statement also terminates the currently active loop or switch statement immediately....

4 minutes read.

C++ Friend Functions

In C++, friends are special functions that are not a part of a class yet have access to its private and protected members. The friend keyword is used to declare...

4 minutes read.

C++ program to read string using cin.getline()

C++ program to read string using cin.getline() C++ getline() is a standard library feature for reading a string or a line from an input source. A getline() function gets characters from...

3 minutes read.

Private Inheritance in C++

Private inheritance is an inheritance in object-oriented programming (OOP) languages where a subclass derives from a superclass. Still, the derived class does not inherit the public and protected members of...

7 minutes read.

Counting Frequencies of Array Elements in C++

We have an array of integer items with duplicate values, and our objective is to compute the frequencies of the different elements in the array. Methods: Methods that can be used to...

3 minutes read.

Vector resize() in C++

Vector resize() in C++ Vectors are called dynamic arrays and can automatically adjust their size when a component is added or deleted. This container is used for storage. The function modifies the...

3 minutes read.

Ways to Copy a Vector in C++

Vectors in C++ are the same as arrays, along with additional outstanding features than them, like array lists in Java programming language. In Vectors, the size constraint is eliminated, which...

5 minutes read.

Virtual Function Vs Pure Virtual Function

Virtual activity is a member function defined in the foundation phase that can be redefined by acquired classes. Let's have a look at an example: #include <iostream>   #include <bits/stdc++.h> #include <stdlib> using namespace std;   class Base   {    ...

5 minutes read.

For Loop Examples in C++

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 of for loop In C++, a...

6 minutes read.

Delete Operator in C++

Overview We can reserve allocation for a variable or an array at runtime in C++. Dynamic memory allocation is the term for this. After utilising a variable in C++, we must...

4 minutes read.

C++ Tricks for Competitive Programming

If you are interested in Computer science or Information technology, you must have heard about competitive programming. Competitive programming is a way to improve your problem-solving skills. There are various...

7 minutes read.

How to calculate size of string in C++

What is string in C++? In C++, a string is a sequence of characters. The string data type is part of the Standard Template Library (STL) and is defined in the...

4 minutes read.

Parameterize Constructor

C++ Parameterized Constructor A constructor having parameters is known as parameterize constructor. Parameterize constructor is used to assign different values. Syntax: className(data-type argument){   // Constructor definition   }   className(data-type argument, data-type argument){   // Constructor definition   } A parameterized constructor can be passed values to constructor function in two ways: 1)...

1 minute read.

C++ Goto

In this article, we will discuss the C++ goto statement with its syntax, use, key features, key points, pseudo code, and examples. What is the goto statement in C++? In C++, the...

4 minutes read.

C++ Math Functions

C++ Math Functions: Like other programming languages, C++ offers plenty of mathematical functions needed for various purposes. These functions are defined mainly in the math library in C++. Let us...

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

Structure Vs Class in C++

The structure in C++ is similar to that of a class, with a few exceptions. Both the structure and the stage, the most important thing is safety. The property is...

4 minutes read.

Accumulate() and partial_sum() in C++ STL Numeric header

The C++ STL's numeric library includes the numeric header. This library provides efficient numeric arrays, support for random number generation, and fundamental mathematical operations and types. Several of the numeric...

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.