reverse every word of given sring

Reversing Every Word in a String in C

To reverse every word in a given string in C, you can follow these steps:

  1. Input the string: Take the input string from the user or initialize it within the code.

  2. Tokenize the string: Split the string into individual words. In C, you can use the strtok function from the <string.h> library to tokenize the string. The strtok function allows you to specify a delimiter (in this case, a space) to split the string into words.

  3. Reverse each word: Iterate through each word obtained from the tokenization step and reverse it. To reverse a word, you can use a two-pointer approach. Set one pointer at the beginning of the word and another at the end. Swap the characters at the two pointers and move the pointers towards each other until they meet in the middle.

  4. Reconstruct the reversed string: After reversing each word, reconstruct the reversed string by concatenating the reversed words together, separated by spaces.

  5. Output the reversed string: Print or return the reversed string.

Here's an example implementation in C:

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

void reverseWord(char* word) {
    int start = 0;
    int end = strlen(word) - 1;

    while (start < end) {
        char temp = word[start];
        word[start] = word[end];
        word[end] = temp;
        start++;
        end--;
    }
}

void reverseString(char* str) {
    char* token = strtok(str, " ");
    while (token != NULL) {
        reverseWord(token);
        token = strtok(NULL, " ");
    }
}

int main() {
    char str[] = "Hello World!";

    reverseString(str);

    printf("Reversed String: %s\n", str);

    return 0;
}

Explanation of the code:

  • The reverseWord function takes a word as input and reverses it using the two-pointer approach.

  • The reverseString function tokenizes the input string using strtok and calls reverseWord on each token to reverse the individual words.

  • In the main function, we initialize a string str with the value "Hello World!". We then call reverseString on str to reverse each word in the string. Finally, we print the reversed string.

Output:

Reversed String: olleH dlroW!

Please note that the code provided is a basic example and may not handle all possible edge cases. It assumes that the input string contains only words separated by spaces.