Monday, May 24, 2010

In Visual C++, how do you reverse a string?

the code that i have so far is:





#include "stdafx.h"


#include %26lt;iostream%26gt;


#include %26lt;iomanip%26gt;


#include %26lt;string%26gt;


using namespace std;


string Reverse(string);





int _tmain(int argc, _TCHAR* argv[])


{


string data = "Hello There";





cout %26lt;%26lt; "The reverse of " %26lt;%26lt; data %26lt;%26lt; " is " %26lt;%26lt; Reverse(data) %26lt;%26lt; endl;





system("PAUSE");


return 0;


}


string Reverse(string x) {





int counter;


string NewString(x);





//enter something here





return NewString;


}

In Visual C++, how do you reverse a string?
reverse( NewString.begin(), NewString.end() );





(You will have to #include %26lt;algorithm%26gt; )
Reply:const string %26amp; reverse( string %26amp; s )


{


return (s = strrev( s.c_str()));


}
Reply:easy... from the top of my head (might need some changes in slight syntax, but heres the idea)





char temp;





for (int x = 0 ; x %26lt; NewString.length() ; x++)


{


//swap two characters


temp = NewString[x];


NewString[x] = NewString[NewString.length()-x ];


NewString[ NewString.length()-x ] = temp;


}





The only things im not sure about are .length(), whether [x] on a string is the right syntax to get a single character, and whether temp should be a string or a char. good luck


No comments:

Post a Comment