summaryrefslogtreecommitdiff
path: root/algorithms/string_reverse.cc
diff options
context:
space:
mode:
Diffstat (limited to 'algorithms/string_reverse.cc')
-rw-r--r--algorithms/string_reverse.cc37
1 files changed, 37 insertions, 0 deletions
diff --git a/algorithms/string_reverse.cc b/algorithms/string_reverse.cc
new file mode 100644
index 0000000..8b3e12c
--- /dev/null
+++ b/algorithms/string_reverse.cc
@@ -0,0 +1,37 @@
+#include <iostream>
+#include <string>
+
+using namespace std;
+
+
+string rev(string &s)
+{
+ string res;
+ for (int i = s.size()-1; i >= 0; i--) { // unsigned not!
+ res += s[i];
+ }
+ return res;
+}
+
+void rev_inplace(string &s)
+{
+ char temp;
+ int j = s.size()-1;
+ for (int i = 0; i < j; i++, j--) {
+ temp = s[i];
+ s[i] = s[j];
+ s[j] = temp;
+ }
+}
+
+
+int main()
+{
+ string s = "Asdf";
+ cout << rev(s) << endl << "---" << endl;
+ cout << s << endl;
+ rev_inplace(s);
+ cout << s << endl;
+ return 0;
+}
+