summaryrefslogtreecommitdiff
path: root/algorithms/string_reverse.c
blob: e6b6988b58461a9fcddcd067047b92df9bebe866 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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;
}