Is there any other way I can make this program better?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
//string reverse algorithm.

#include <iostream>
#include <string>

using std::cout;
using std::cin;
using std::endl;
using std::string;

int main()
{
	cout << "Input: ";

	string input;

	getline(cin, input);

	char *output = new char[input.length() + 1];

	strcpy(output, input.c_str());

	output[input.length()] = '\0';

	char *reverse = new char[input.length() + 1];

	for(int i = 0; i < input.length(); i++) 
	{
		reverse[i] = output[input.length() - 1 - i];
	}

	reverse[input.length()] = '\0';

	cout << "Output: " << reverse;

	delete output, reverse;

	cout << endl << endl << "Press any key to continue.";

	std::getchar();
}
Last edited on
Well, the main secret is that you can reverse the string "in place" i.e. without allocating new memory. Swap the last char with the first etc.

Also I should say that if you prefer work with C-like strings (i.e. array of chars) you need not use "string":

1
2
3
4
5
6
char s[256];
gets(s); // read string from console
int n = strlen(s);
for (int i = 0; i < n / 2; i++) {
    // swap i-th character with (n-i-1)-th
}


Here is this task at my site:

http://codeabbey.com/index/task_view/reverse-string

And here is "rotating" the string which could be done in-place too with two reversion - i.e. the task is based on "reverse":

http://codeabbey.com/index/task_view/rotate-string
Last edited on
Since this is C++, I would just stick with std::string unless you have a real reason to use char arrays instead (and even if you do, you can just use the .c_str() member function of std::strings instead).

That being said, on line 36, it should be
1
2
delete[] output;
delete[] reverse;

since you allocated them using new[].

Also, I don't think you can put them both on one line like that, because it'll only delete the first one. (Look up the comma operator here: http://www.cplusplus.com/doc/tutorial/operators/ . Basically, delete output, reverse; runs delete output; and then returns reverse)

But really, you should be using std::string.
If you're not being required to write your own reverse function (i.e. for an assignment), there's a really easy way to reverse a string:
1
2
3
std::string str = "Hi there!";
std::string reverse(str.rbegin(), str.rend());
std::cout << reverse;
!ereht iH

If you need/want to reverse in-place, look at std::reverse:
http://www.cplusplus.com/reference/algorithm/reverse/
Topic archived. No new replies allowed.