Created
June 12, 2021 16:55
-
-
Save airicbear/b0c90697f9c073dba2abea3835c5daab to your computer and use it in GitHub Desktop.
Reverse a 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 <stdio.h> | |
#include <string.h> | |
char* reverse(char* in); | |
void swap(char* s, int a, int b); | |
int main(int argc, char** argv) { | |
if (argv[1]) { | |
printf("%s\n", reverse(argv[1])); | |
} else { | |
fprintf(stderr, "Please specify a word.\n"); | |
} | |
return 0; | |
} | |
char* reverse(char* in) { | |
int len = strlen(in); | |
for (int i = 0; i < len / 2; i++) { | |
swap(in, i, len - i - 1); | |
} | |
return in; | |
} | |
void swap(char* s, int a, int b) { | |
char tmp = s[a]; | |
s[a] = s[b]; | |
s[b] = tmp; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment