Reversing a string

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
string tekst;
	cout << "enter a string: ";
	getline(cin, tekst);
	int size = tekst.length();
	
	for (int i = 0; i < size /2; i++)
	{
		string tempvar1 = tekst.substr(i);
		string tempvar2 = tekst.substr(size - 1 - i);
		tekst.replace(i, i+1, tempvar2);
		tekst.replace(size - 1 -i, (size - 1 - i) + 1, tempvar1);
	}

	cout << tekst << endl;
	return 0;


That code doesn't work. It displays the inserted string for like 100 times now :S

What's wrong with this?
It should reverse a string

For example: "this is a test" should become "test a si siht"
Last edited on
You can do this in a single line: tekst = string ( tekst.rbegin(), tekst.rend() );
Thank you Bazzy.

Can you explain that line? I mean, what are the rbegin() methods and why use the function string()?

EDIT:
Ok, I understand rbegin() and rend(), but what about that function string()?
Last edited on
string ( ) is the string constructor which creates a new string object ( http://www.cplusplus.com/reference/string/string/string/ )

rbegin and rend are reverse iterators, an iterator is an object which acts in a similar way to a pointer ( http://www.cplusplus.com/reference/std/iterator/reverse_iterator/ http://www.cplusplus.com/reference/string/string/rbegin/ )
string ( tekst.rbegin(), tekst.rend() ) creates a string from the beginning to the of the reversed 'tekst'
Ok, thank you very much =)
Topic archived. No new replies allowed.