Reverse array

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Example program
#include <iostream>
#include <string>

std::string reverse(const std::string& str)
{
    return std::string(str.rbegin(), str.rend()); // "reverse begin" and "reverse end"
}

int main()
{
    std::string s = "John";
    std::cout << reverse(s) << std::endl;
}
Last edited on
is there a way to do it with char?

int stringLength(const char *str);
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.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <cstring>
using namespace std;

char *rev( char * str )
{
   int sz = strlen( str );
   char * rts = new char[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.
Last edited on
@lastchance,
what about letting the caller provide a string for the output - like in the WIN API?
 
char *rev (const char * input, char *output )
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.
Topic archived. No new replies allowed.