posted:
Hi There,
Can you please help me write an in-place function in C++ for reversing
a string.
What is an in-place function?
So what is a non-in-place function in that case to reverse a C++
string?
Urgent help needed.
Thanks,
Peter.
This problem is so trivial that I'd challenge myself as to just how
efficient I can make it.
(Yes I realise I'm doing your homework, but this could be a laugh...)
The following code is unchecked and most likely doesn't work, but what the
hey:
#include <cstddef>
#include <cstring>
#include <iostream>
using std::cout; using std::endl;
/* The actual function */
void ReverseString( char* p_beginning, char* p_end )
{
for (;;)
{
std::swap( *p_beginning, *p_end );
switch (p_end++ - p_beginning++)
{
case 1: case 2: return;
}
}
}
/* The function whose argument is an array */
template<std::s ize_t i>
void ReverseString( char (&p_start)[i] )
{
ReverseString( &p_start[0], &p_start[i - 1] );
}
/* The function which takes a pointer, and also an integral length */
void ReverseString( char* const p_str, std::size_t len )
{
ReverseString( &p_str[0], &p_str[--len] );
}
/* The function which take a pointer */
void ReverseString( char* const p_start )
{
ReverseString( p_start, std::strlen(p_s tart) );
}
int main()
{
char monkey[] = "monkey";
char cow[] = "cow";
char niagra[] = "niagra";
char stringent[] = "stringent" ;
ReverseString( monkey ); ReverseString(c ow); ReverseString(n iagra);
ReverseString( &monkey[0] ); ReverseString( &cow[0] );
cout << monkey << cow << niagra << stringent;
}
-Tomás