The task was to reverse the order of words in the sentence I was able to reverse the order of the words, but the problem is that the order of the letters in the word also changes
For example: cats and dogs
The miracle in my plan:tac dna sgod
The desired output: dogs and cats
How can I fix the code to work correctly?
this is my code:
void revSent(char str[]) {
int i;
int n = strlen(str);
char letter;
for (i = 0; i < n / 2; i ) {
letter = str[i];
str[i] = str[strlen(str) - i - 1];
str[strlen(str) - i - 1]=letter ;
}
}
CodePudding user response:
You could split your sentence with the whitespace and then you can reorder the resulting array in reverse.
CodePudding user response:
The usual approach is to reverse the whole string and then to reverse each word in the string separately.
To extract words in a string you can use standard string functions strspn
and strcspn
.
Here is a demonstration program
#include <stdio.h>
#include <string.h>
void reverse_n( char *s, size_t n )
{
for (size_t i = 0; i < n / 2; i )
{
char c = s[i];
s[i] = s[n - i - 1];
s[n - i - 1] = c;
}
}
char *revSent( char *s )
{
const char *blank = " \t";
reverse_n( s, strlen( s ) );
for (char *p = s; *p; )
{
p = strspn( p, blank );
if (*p)
{
size_t n = strcspn( p, blank );
reverse_n( p, n );
p = n;
}
}
return s;
}
int main( void )
{
char s[] = "cats and dogs";
puts( s );
puts( revSent( s ) );
}
The program output is
cats and dogs
dogs and cats