reversing a string

I was wondering if it's possible to reverse a string?
Yes.
Ok thanks.
Wow.
Laconic thread.
Precisely. :-)
.......not any more..........
If the string is held by an array you can access each element progressively from the end in a for loop and place each in a second array starting with its first element.
Another way is to set two pointers, pa* to element [0] and pb* to sizeof -1. Swap the elements being pointed to using a swap() function from the STL and then increment pa++ and decrement pb--. Repeat until reversal complete.
Last edited on
You just had to ruin the joke, didn't you?
The standard library provides a function "reverse" to achieve an in place reversal of some collections (including strings). For example:
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <algorithm>
#include <string>

int main( void )
{
	std::string test( "reverse" );
	std::reverse( test.begin(), test.end() );
	std::cout << test << std::endl;
	return 0;
}


Hope this helps,
CC
Last edited on
Topic archived. No new replies allowed.