Skip to content

Instantly share code, notes, and snippets.

@frank4565
Last active August 29, 2015 13:56
Show Gist options
  • Save frank4565/8931107 to your computer and use it in GitHub Desktop.
Save frank4565/8931107 to your computer and use it in GitHub Desktop.
1.2 Implement a function void reverse(char* str) in C or C++ which reverses a null- terminated string.
#include<iostream>
void reverse(char *str) {
if (str == nullptr) return;
// find the end of the string
char *end = str;
char temp;
while (*end != '\0') ++end;
--end;
// swap the begin and end
while (str < end) {
temp = *str;
*str++ = *end;
*end-- = temp;
}
}
int main(int argc, char *argv[])
{
char str[]{"abcde"};
reverse(str);
std::cout << str << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment