-
Reversing A String?
I need to know how to reverse a string using C++?
I have been told the best way to do this is by using Pointers but I am unable to find a way to make it work. :(
And, yes I am aware there is probably a really easy way to do this but my brain isn't working.
-
Hi,
using MFC(CString) but same algorythm should work for other strings, too.
(except index might be zero-based)
--------------------the function-----
CString CReverseStringDlg::ReverseString( CString* string_in )
{
CString aTempString;
unsigned int aStrlen = string_in->GetLength();
TCHAR ch;
for ( unsigned int i = 1; i <= aStrlen; i++ )
{
ch = string_in->GetAt( aStrlen - i );
aTempString.Insert( i, ch );
}
return ( aTempString );
}
--------------------the call------------
CString aString;
aString = "123456789";
aString = ReverseString( &aString );
// now aString is "987654321"
Have fun.
-
Hi. Thanks for the quick reply. I actually managed to find a soloution of my own :-)
If your interested;
void displayinreverse()
{
cout << "The Text Reversed Is: ";
string name = line; // line is the variable used in the cin
int nLength=name.length();
for (int i=nLength-1;i>=0;i--)
cout << line[i];
cout << endl;
}
Thanks again for your help though :-)
-
using strrev function...
Code:
#include<iostream.h>
#include<string.h>
int main()
{
char bud[255];
cout<<"Enter a string\n";
cin.getline(bud, 255, '\n');
cout<<"\nString before reversal: \n";
cout<<bud;
cout<<"\n";
strrev(bud);
cout<<"\nString after reversal: \n";
cout<<bud;
cout<<"\n";
return 0;
}
using a loop...
Code:
#include<iostream.h>
#include<string.h>
int main()
{
char BAK[255]="", bud[255]="";
int h,i;
cout<<"Enter a string\n";
cin.getline(bud, 254,'\n');
cout<<"\nString before reversal: \n";
cout<<bud;
cout<<"\n";
i = strlen(bud);
for(h=0; i>0; i--)
{
BAK[h] = bud[i-1];
h++;
}
cout<<"\nString after reversal: \n";
cout<<BAK;
return 0;
}
-
heres how to do it with pointers....
Code:
void Reverse(char* pData)
{
char temp; //holding area
int Length=strlen(pData);
char* start=pData; //first char
char* last=pData+Length-1;//last char before null
while (start<last) // stops at midpoint
{
temp=*start;
*start=*last;
*last=temp;
++start;
--last;
}
}