Last active
August 29, 2015 13:56
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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