You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Input : s = "getting good at coding needs a lot of practice"
38
+
Output : s = "practice of lot a needs coding at good getting"
39
+
Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.
40
+
Algorithm:
41
+
42
+
1) Reverse the individual words, we get the below string.
43
+
"i ekil siht margorp yrev hcum"
44
+
2) Reverse the whole string from start to end and you get the desired output.
45
+
"much very program this like i"
46
+
#include<stdio.h>
47
+
48
+
/* function prototype for utility function to
49
+
reverse a string from begin to end */
50
+
void reverse(char *begin, char *end);
51
+
52
+
/*Function to reverse words*/
53
+
void reverseWords(char *s)
54
+
{
55
+
char *word_begin = s;
56
+
char *temp = s; /* temp is for word boundry */
57
+
58
+
/*STEP 1 of the above algorithm */
59
+
while( *temp )
60
+
{
61
+
temp++;
62
+
if (*temp == '\0')
63
+
{
64
+
reverse(word_begin, temp-1);
65
+
}
66
+
else if(*temp == ' ')
67
+
{
68
+
reverse(word_begin, temp-1);
69
+
word_begin = temp+1;
70
+
}
71
+
} /* End of while */
72
+
73
+
/*STEP 2 of the above algorithm */
74
+
reverse(s, temp-1);
75
+
}
76
+
77
+
/* UTILITY FUNCTIONS */
78
+
/*Function to reverse any sequence starting with pointer
79
+
begin and ending with pointer end */
80
+
void reverse(char *begin, char *end)
81
+
{
82
+
char temp;
83
+
while (begin < end)
84
+
{
85
+
temp = *begin;
86
+
*begin++ = *end;
87
+
*end-- = temp;
88
+
}
89
+
}
90
+
91
+
/* Driver function to test above functions */
92
+
int main()
93
+
{
94
+
char s[] = "i like this program very much";
95
+
char *temp = s;
96
+
reverseWords(s);
97
+
printf("%s", s);
98
+
getchar();
99
+
return 0;
100
+
}
101
+
Run on IDE
102
+
Output:
103
+
104
+
much very program this like i
105
+
The above code doesn’t handle the cases when the string starts with space. The following version handles this specific case and doesn’t make unnecessary calls to reverse function in the case of multiple space in between. Thanks to rka143 for providing this version.
106
+
107
+
void reverseWords(char *s)
108
+
{
109
+
char *word_begin = NULL;
110
+
char *temp = s; /* temp is for word boundry */
111
+
112
+
/*STEP 1 of the above algorithm */
113
+
while( *temp )
114
+
{
115
+
/*This condition is to make sure that the string start with
0 commit comments