Reverse Words in a String Using Function in C

Reversing the order of words in a string is a common string manipulation problem. For example, transforming "I LOVE INDIA" to "INDIA LOVE I" can be accomplished using a function in C.

This exercise helps understand string handling, functions, and pointers in C.

Logic to Reverse Words in a String

1. Split the string into words by identifying spaces.

2. Store each word in an array of strings or pointers.

3. Print the words in reverse order.

4. This can be done using a function that takes the original string and prints the reversed word order.

C Program to Reverse Words Using a Function

C
Function to reverse words in a string
#include <stdio.h>
#include <string.h>

void reverseWords(char str[]) {
    int i, j, start;
    int len = 0;
    char words[10][50]; // assuming max 10 words, each max 50 chars
    int wordCount = 0;

    // Manually find length
    while(str[len] != '\0') len++;

    i = 0;
    while(i <= len) {
        if(str[i] == ' ' || str[i] == '\0') {
            words[wordCount][j] = '\0';
            wordCount++;
            j = 0;
        } else {
            words[wordCount][j++] = str[i];
        }
        i++;
    }

    // Print words in reverse order
    for(i = wordCount - 1; i >= 0; i--) {
        printf("%s", words[i]);
        if(i != 0) printf(" ");
    }
    printf("\n");
}

int main() {
    char str[] = "I LOVE INDIA";
    printf("Original String: %s\n", str);
    printf("Reversed Words: ");
    reverseWords(str);
    return 0;
}
Output:
Original String: I LOVE INDIA
Reversed Words: INDIA LOVE I

Explanation

• The function 'reverseWords' extracts words by checking for spaces or the null character.

• Each word is stored in a 2D array 'words'.

• After storing all words, a loop prints them in reverse order.

• This method does not alter the original string, it just prints the words reversed.

Advantages of Using Function

• Makes the code modular and reusable.

• Easier to maintain and understand.

• Can handle strings of different lengths and number of words (adjusting array sizes).

Conclusion

Reversing words in a string using a function is an effective way to manage string manipulations in C. It introduces concepts of arrays, loops, string indexing, and modular programming. This approach can be extended to handle dynamic strings and larger inputs.