Header Ads Widget

Write a program to reverse a string

Write a program to reverse a string

Here some different ways to reverse a string .
  1. By using for loop
  2. By using while loop
  3. By using range-based for loop
  4. By using reverse function
1. By using for loop

In this example code, we first declare a string str and initialize it with a value. We then declare another string reversedStr and initialize it with an empty string.

We then loop through the characters of the str string starting from the last character and append each character to the reversedStr string.

Finally, we print both the original and reversed strings to the console.

Code(C++):-


#include <iostream>
#include <string>
using namespace std;

int main() {
  string str = "Hello, world!";
  string reversedStr = "";

  for(int i = str.length() - 1; i >= 0; i--) {
    reversedStr += str[i];
  }

  cout << "Original string: " << str << endl;
  cout << "Reversed string: " << reversedStr << endl;

  return 0;
}

Output:-

Original string: Hello, world!
Reversed string: !dlrow ,olleH


2.By using while loop:-

#include <iostream>
#include <string>
using namespace std;

int main() {
  string str = "Hello, world!";
  string reversedStr = "";
  int i = str.length() - 1;

  while(i >= 0) {
    reversedStr += str[i];
    i--;
  }

  cout << "Original string: " << str << endl;
  cout << "Reversed string: " << reversedStr << endl;

  return 0;
}

Output:-

Original string: Hello, world!
Reversed string: !dlrow ,olleH


3. By using range-based for loop:-

#include <iostream>
#include <string>
using namespace std;

int main() {
  string str = "Hello, world!";
  string reversedStr = "";

  for(char c : str) {
    reversedStr = c + reversedStr;
  }

  cout << "Original string: " << str << endl;
  cout << "Reversed string: " << reversedStr << endl;

  return 0;
}

Output:-

Original string: Hello, world!
Reversed string: !dlrow ,olleH


4. by using reverse() function:-

#include <iostream>
#include <string>
using namespace std;

int main() {
  string str = "Hello, world!";

  // Using the reverse() function to reverse the string
  reverse(str.begin(), str.end());

  cout << "Original string: " << "Hello, world!" << endl;
  cout << "Reversed string: " << str << endl;

  return 0;
}

Questions About Accenture:-

Recommended Post :-




Post a Comment

0 Comments