Hi here is how I approached the problem:
-First we need to make a function that reverses a word given a pointer pointing towards the begining of that word and the length of the word.
Code:
void rev_chars(char *str, int n)
{
int i;
char swap;
//this will work reagardless of wether the length of the word is even or odd
for (i = 0; i < n / 2; i++)
{
swap = str[i];
str[i] = str[n - i - 1];
str[n - i - 1] = swap;
}
}
-Then we need to make a function that searches for every words, measure their length and calls the prevoius function
Code:
void rev_words(char *str)
{
int i = 0;
int j;
while (str[i])
{
//skiping unnecessary space
while (str[i] == ' ')
i++;
//the we measure the length of the word
j = 0;
while (str[i + j] != ' ' && str[i + j])
j++;
//caling the preious funtction
rev_chars(str + i , j);
//go to the next set of spaces
i += j;
}
}
Be carefull, this function is "destructive", meaning that it will aply changes directly on the string that we give it.
If you want this function to return a copy with the desired changes you will need to use malloc.
But, given the problem, I guess this is kind of out of the scope of this thread.
Anyway, I hope this answer helped.
full code with main to test if the function works(it sould
how knows...):
Code:
#include<stdio.h>
void rev_chars(char *str, int n)
{
int i;
char swap;
for (i = 0; i < n / 2; i++)
{
swap = str[i];
str[i] = str[n - i - 1];
str[n - i - 1] = swap;
}
}
void rev_words(char *str)
{
int i = 0;
int j;
while (str[i])
{
while (str[i] == ' ')
i++;
j = 0;
while (str[i + j] != ' ' && str[i + j])
j++;
rev_chars(str + i , j);
i += j;
}
}
int main(int ac, char **av)
{
int i;
for(i = 0; i < ac; i++)
{
rev_words(av[i]);
printf("%s\n", av[i]);
}
}