Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

string inversion

Status
Not open for further replies.

Lynch1975

Programmer
Feb 21, 2003
1
0
0
CA
I would like to know the BEST way for a function, to invert a string received by pointer. Do you have code to propose? Number of parameters is free. Thanks
 
bool inverse(char *szStr)
{
char *pnts;
char *pntd;
char *buffer;
int ii;
bool retc=0;

ii=strlen(szStr);
buffer=new char[ii];
if(buffer!=NULL)
{
pntd=buffer;
pnts=szStr+ii;
while(pnts>szStr) *(pntd++)=*(--pnts);
*pntd=0;
strcpy(szStr, buffer);
retc=1;
delete buffer;
}

return(retc);
}
 
Just another approach

Code:
void inverse(char* buffer)
{
 int end = strlen(buffer)-1;
 int begin = 0;

 for(;begin<end;begin++,end--)
 {
   buffer[begin]^=buffer[end]^=buffer[begin]^=buffer[end];
 }
}

Matt
 
All goes to prove how starting with the right language and question produces the right solution! I followed a thread once on reversing a string without using any additional storage. Somehow that limitation forced everyone to think about methods that did use storage, and everyone was bursting into assembler and pushing things onto stacks and all that stuff. It was ages before anyone realised you just swap pairs of letters working your way towards the middle of the string.

(oh, if anyone wants an assembler version, I'll post it)
 
Here is a very simple way to do it:

Code:
#include <iostream.h>
#include <string.h>

char *inverse( char *str )
{
	unsigned int len = strlen(str);
	char *cp = new char[len+1];
    int j = 0;
	
	for( int i = len - 1; i >= 0; i-- )
	{
		cp[j] = str[i];
		j++;
	}
	cp[j] = 0;
	strcpy( str, cp );

	delete cp;
	return str;
}


void main()
{
	char str[20] = {&quot;Hello world !&quot;};
	cout<<inverse(str)<<endl;
}

// output: ! dlrow olleH
 
Perhaps we should pay heed to lionelhill's sage advice:

void InvertInPlace(char *ptr)
{
char *start = ptr;
char *end = ptr;
while (*end)
++end;
int delta = end - start;
if (delta < 2)
return;
--end;
char *mid = &ptr[(delta + 1) / 2];
while (ptr < mid)
{
char temp = *end;
*end = *ptr;
*ptr = temp;
--end;
++ptr;
}
}

Newton
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top