forked from AllAlgorithms/cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverse_string.cpp
More file actions
62 lines (56 loc) · 1.31 KB
/
reverse_string.cpp
File metadata and controls
62 lines (56 loc) · 1.31 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
//
// Reverse String in C++
//
// The All ▲lgorithms Project
//
// https://allalgorithms.com/strings
// https://github.com/allalgorithms/cpp
//
// Contributed by: Tushar Kanakagiri
// Github: @tusharkanakagiri
//
#include <stdio.h>
/* function prototype for utility function to
reverse a string from begin to end */
void reverse(char* begin, char* end);
/*Function to reverse words*/
void reverseWords(char* s)
{
char* word_begin = s;
char* temp = s; /* temp is for word boundry */
/*STEP 1 of the above algorithm */
while (*temp) {
temp++;
if (*temp == '\0') {
reverse(word_begin, temp - 1);
}
else if (*temp == ' ') {
reverse(word_begin, temp - 1);
word_begin = temp + 1;
}
} /* End of while */
/*STEP 2 of the above algorithm */
reverse(s, temp - 1);
}
/* UTILITY FUNCTIONS */
/*Function to reverse any sequence starting with pointer
begin and ending with pointer end */
void reverse(char* begin, char* end)
{
char temp;
while (begin < end) {
temp = *begin;
*begin++ = *end;
*end-- = temp;
}
}
/* Driver function to test above functions */
int main()
{
char s[] = ""; //Enter string here
char* temp = s;
reverseWords(s);
printf("%s", s);
getchar();
return 0;
}