Code:
#include <iostream>
#include <string>
using namespace std;
// swaps given two characters
void swap(char& a, char& b) {
char temp = a;
a = b;
b = temp;
}
/* reverses string by swapping first character with last character
* second character with second to last character, third character with
* third to last character, etc.
*/
string reverse(string source) {
int len = source.length();
int count;
for (count = 0; count < len/2; count++) {
swap(source[count], source[len-count-1]);
}
return source;
}
/* tests string reversal by outputting string before reversing it,
* reversing the string and outputting the reversed string, and then
* reversing it again to see if the twice reversed string is the same as
* the original
*/
bool test(string& testString) {
string copy = reverse(testString);
cout << "String before reversing: " << testString<< "\n";
cout << "String after reversing : " << copy << "\n";
copy = reverse(copy);
if ( copy == testString) {
cout << "It may have worked" << endl;
return true;
}
else {
cout << "It did not work" << endl;
return false;
}
}
// calls test for an array of strings
int main(int argc, char *argv[])
{
string testStringArray[] = {"Rob", "Words", "SilentStrikeIsHelpingYouOut",
"radar", "five"};
// ugly way of finding out how many strings are in array, but will work if
// more strings are added to the array
int arrayLen = sizeof testStringArray / sizeof testStringArray[0];
int count;
for (count = 0; count < arrayLen; count++) {
test(testStringArray[count]);
}
char wait; cin >> wait;
return 0;
}