Reverse every Word of given String

Code Explanation

#include <stdio.h>
#include <string.h>

void reverseWords(char* s) {
    int start = 0;
    for (int end = 0; s[end] != '\0'; end++) {
        if (s[end] == ' ') {
            for (int i = end - 1; i >= start; i--) {
                printf("%c", s[i]);
            }
            printf(" ");
            start = end + 1;
        }
    }
    for (int i = strlen(s) - 1; i >= start; i--) {
        printf("%c", s[i]);
    }
}

int main() {
    char str[] = "Hello World, how are you?";
    reverseWords(str);
    return 0;
}

Explanation

The given C code defines a function reverseWords that takes a string s as input and reverses every word in the string. It then defines a main function to demonstrate the usage of the reverseWords function.

  1. The reverseWords function iterates through the input string s character by character.
  2. It identifies the words by detecting spaces and then reverses each word individually.
  3. The reversed words are printed to the console.

The main function initializes a string "Hello World, how are you?" and calls the reverseWords function to reverse the words in the string.

This code effectively reverses every word in the given string.

[[SOURCE 1]]