how would i write a function that would take an array of characters and return the characters reversed.For example, passing test will return tset, John will return nhoJ
Yes you can reverse a C-string, but probably not a const C-string unless you have somewhere else to place the reversed C-string. And don't forget to insure the C-string is properly terminated.
to reverse a c-string in place just do this
for(first = 0, last = strlen(str)-1; first<= last; first++ last--)
swap(str[first, str[last]);
the length of the swapped string is the same, and the zero terminal is untouched, so all should be well if I got the indexing right.
#include <iostream>
#include <cstring>
usingnamespace std;
char *rev( char * str )
{
int sz = strlen( str );
char * rts = newchar[sz+1];
for ( int i = 0; i < sz; i++ ) rts[i] = str[sz-1-i];
rts[sz] = 0;
return rts;
}
int main()
{
char text[] = "Hello";
char *back = rev( text );
cout << text << "--->" << back << '\n';
delete [] back;
}
Harder to reverse a const c-string. The only way I could declare and initialise it together was to copy into a non-const string (or std::string) first.
I've never used the win API.
I would want to return like-for-like, so if sending a const char[] then I would want to return a const char *, and as the return value of the function, too.