C++ program to reverse given string.

Sample Input:

In:
Hello World!
theflyingkeyboard.net
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Out:
!dlroW olleH
ten.draobyekgniylfeht
.auqila angam erolod te erobal tu tnudidicni ropmet domsuie od des ,tile gnicsipida rutetcesnoc ,tema tis rolod muspi meroL

Code:

// © 2017 TheFlyingKeyboard and released under MIT License
// theflyingkeyboard.net 

#include <iostream>
#include <string>

using namespace std;

string reverseString(string stringToReverse);

int main(){
  string stringToReverse;
  
  cout << "Enter a string you want to reverse" << endl;
  getline(cin, stringToReverse);
  
  cout << reverseString(stringToReverse) << endl;
  
  return 0;
}

string reverseString(string stringToReverse){
  char tmp;
  
  for(int i = 0; i < stringToReverse.size() / 2; i++){
    tmp = stringToReverse[stringToReverse.size() - 1 - i];
    stringToReverse[stringToReverse.size() - 1 - i] = stringToReverse[i];
    
    stringToReverse[i] = tmp;
  }
  
  return stringToReverse;
}

 

C++ Reverse A String
Tagged on:     

Leave a Reply

Your email address will not be published. Required fields are marked *

This website stores some user agent data. These data are used to provide a more personalized experience and to track your whereabouts around our website in compliance with the European General Data Protection Regulation. If you decide to opt-out of any future tracking, a cookie will be set up in your browser to remember this choice for one year. I Agree, Deny
504