Search⌘ K
AI Features

Solution: Reverse the Words

Explore how to reverse individual words within a string in C by manipulating character arrays. Understand the use of pointers and functions like strlen to efficiently reverse substrings, enhancing your skills in handling strings and arrays in C.

We'll cover the following...
C
#include <stdio.h>
#include <string.h>
/* Function to reverse a portion of the string */
void reverse(char *str, int start, int end) {
while (start < end) {
char temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
int main() {
char sentence[] = "C programming is fun";
int len = strlen(sentence);
/* Step 1: Reverse the entire string */
reverse(sentence, 0, len - 1);
/* Step 2: Reverse each word */
int start = 0;
for (int i = 0; i <= len; i++) {
if (sentence[i] == ' ' || sentence[i] == '\0') {
reverse(sentence, start, i - 1);
start = i + 1;
}
}
printf("%s\n", sentence);
return 0;
}
...