Skip to content

Instantly share code, notes, and snippets.

@MicBrain
Created September 15, 2015 07:38
Show Gist options
  • Save MicBrain/08440c1cc2c4f6739247 to your computer and use it in GitHub Desktop.
Save MicBrain/08440c1cc2c4f6739247 to your computer and use it in GitHub Desktop.
/* Problem 1.2: Implement a function void reverse(char* str)
* in C or C++, which reverses a null-terminated string.
* @author: Rafayel Mkrtchyan
* @date: 9/14/2015
*/
#include <iostream>
/* This function takes an iterative approach to problem
* using an O(n) speed.
*/
void reverse_string(char* str) {
char* sameStr = str;
char temporary;
if (str) {
while(*sameStr) {
++sameStr;
}
--sameStr;
while (str < sameStr) {
temporary = *str;
*str++ = *sameStr;
*sameStr-- = temporary;
}
}
}
int main() {
std::string str = "Berkeley";
char* writable = new char[str.size() + 1];
std::copy(str.begin(), str.end(), writable);
writable[str.size()] = '\0';
reverse_string(writable);
std::cout << writable << std::endl;
delete[] writable;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment