diff options
Diffstat (limited to 'algorithms/string_reverse.c')
-rw-r--r-- | algorithms/string_reverse.c | 42 |
1 files changed, 42 insertions, 0 deletions
diff --git a/algorithms/string_reverse.c b/algorithms/string_reverse.c new file mode 100644 index 0000000..e6b6988 --- /dev/null +++ b/algorithms/string_reverse.c @@ -0,0 +1,42 @@ +#include <stdio.h> +#include <string.h> + + +char * rev(char *s) +{ + int l = strlen(s); + char res[l+1]; + int k = 0; + for (int i = l-1; i >= 0; i--) { // unsigned not! + res[k] = s[i]; + k++; + } + res[l] = 0; + return res; +} + +void rev_inplace(char *s) +{ + char temp; + int j = strlen(s)-1; + for (int i = 0; i <= j; i++) { + temp = s[i]; + s[i] = s[j]; + s[j] = temp; + j--; + } +} + + +int main(void) +{ + char *s = "Asdf"; + printf("%s\n", s); + char *r = rev(s); + printf("%s\n", r); + char t[] = "fdsA"; + rev_inplace(t); + printf("%s\n", t); + return 0; +} + |