We need to decompose into two problems. We already have most of the solution to one problem (reversing a string); we just need to make it work with a substring. We do this mainly by removing the code that finds the end of the string:
/* reverse substring [left, right) in-place */
void reverseSubstring(char *left, char *right)
{
while (left < --right) {
char c = *right;
*right = *left;
*left++ = c;
}
}
The other half of the problem is finding the boundaries between words. We can use isspace()
to position start and end pointers in the right places, and call our reverseSubstring
with them:
#include <ctype.h>
char *reversepPrint(char *const name)
{
char *start = name;
char *end;
while (*start) {
while (*start && isspace(*start)) {
++start;
}
end = start;
while (*end && !isspace(*end)) {
++end;
}
reverseSubstring(start, end);
start = end;
}
return name;
}
If you're also prohibited from using <ctype.h>
, it isn't hard to write a simple isspace()
of your own for this function.
Full program
/* reverse substring [left, right) in-place */
void reverse_substring(char *left, char *right)
{
while (left < --right) {
char c = *right;
*right = *left;
*left++ = c;
}
}
#include <ctype.h>
/* reverse individual words in string */
/* word boundaries determined by isspace() */
char *reverse_words(char *const name)
{
for (char *start = name, *end; *start; start = end) {
while (*start && isspace(*start)) { ++start; }
end = start;
while (*end && !isspace(*end)) { ++end; }
reverse_substring(start, end);
}
return name;
}
#include <stdio.h>
int main(void)
{
char s[] = "Simon liebt Pizza!";
printf("%s", reverse_words(s));
}