-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverse_string.c
More file actions
99 lines (75 loc) · 1.49 KB
/
reverse_string.c
File metadata and controls
99 lines (75 loc) · 1.49 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/* String.h includes one variable type, one macro, and several functions for
manipulating arrays of characters.*/
void reverseWithRecursion(char*, int , int); //Function definitions
/*void reverseFunction(char *string)
{
strrev(string);
}*/
char *reverseWithoutFunction(char *string)
{
char *reverse;
int n, c, d;
n = strlen(string);
reverse = (char*)malloc(n * 1);
for (c = n - 1, d = 0; c >= 0; c--, d++){
reverse[d] = string[c];
}
reverse[d] = '\0';
return (char *)reverse;
}
int stringLength(char *pointer)
{
int c = 0;
while( *(pointer + c) != '\0')
{
c++;
}
return c;
}
void reverseWithPointer(char *string)
{
int length, c;
char *begin, *end, temp;
length = stringLength(string);
begin = string;
end = string;
for (c = 0; c < length - 1; c++)
{
end ++;
}
for (c = 0; c < length/2; c++)
{
temp = *end;
*end = *begin;
*begin = temp;
begin ++;
end --;
}
}
void reverseWithRecursion(char *x, int begin, int end)
{
char c;
if(begin>= end)
{
return;
}
c = *(x+begin);
*(x+begin) = *(x+end);
*(x+end) = c;
reverseWithRecursion(x, ++begin, --end);
}
int main()
{
char arr[100];
char *rev;
printf("Enter a string to reverse\n");
gets(arr); //reads string in from stdin and stores into string pointed to by arr.
//rev = reverseWithoutFunction(arr);
//reverseWithPointer(arr);
reverseWithRecursion(arr, 0, strlen(arr)-1);
printf("Reverse of entered string is \n%s\n", arr);
return 0;
}