Write c function to reverse words in sentence (without using external arrays)
Question
Write c function to reverse words in sentence (without using external arrays)
Solution
Here is a C function to reverse words in a sentence without using external arrays. This function uses two pointers to track the start and end of a word and then reverses the word in place.
#include <stdio.h>
#include <string.h>
void reverse(char* begin, char* end) {
char temp;
while (begin < end) {
temp = *begin;
*begin++ = *end;
*end-- = temp;
}
}
void reverseWords(char* s) {
char* word_begin = s;
char* temp = s;
while (*temp) {
temp++;
if (*temp == '\0') {
reverse(word_begin, temp - 1);
} else if (*temp == ' ') {
reverse(word_begin, temp - 1);
word_begin = temp + 1;
}
}
reverse(s, temp - 1);
}
int main() {
char s[] = "Hello World";
reverseWords(s);
printf("%s", s);
return 0;
}
This program works by first reversing each word in the sentence, and then reversing the entire sentence. This results in the words being in the original order, but the characters within each word are reversed.
Similar Questions
Write a program in C to print a string in reverse using a character pointer.Also print the uppercase of the first letter of the reversed word.Sample InputwordSample OutputdrowD
Write a C program to find reverse of a string using pointers
Write a C function, which reverses a given string and returns a pointer to reversed string.char *reverse(char *str);
In a given sentence or an array of characters, reverse the order of words.
Reversing a string in C is a fundamental operation that involves rearranging the characters in a string so that the last character becomes the first, the second-to-last character becomes the second, and so on.
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.