Q:

C program to reverse every word of the given string

belongs to collection: C String Programs

0

C program to reverse every word of the given string

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Read a string and then reverse every word of the given string using C program.

Program:

The source code to reverse every word of the given string is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to reverse every word of given string

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

int main()
{
    char str[64];
    char words[6][10];
    char temp;

    int i = 0;
    int j = 0;
    int k = 0;
    int ii = 0;
    int l = 0;

    printf("Enter string: ");
    scanf("%[^\n]s", str);

    while (str[i] != 0) {
        if (str[i] == ' ') {
            words[k][j] = '\0';
            k++;
            j = 0;
        }
        else {
            words[k][j] = str[i];
            j++;
        }
        i++;
    }
    words[k][j] = '\0';

    for (i = 0; i <= k; i++) {
        l = strlen(words[i]);

        for (j = 0, ii = l - 1; j < ii; j++, ii--) {
            temp = words[i][j];
            words[i][j] = words[i][ii];
            words[i][ii] = temp;
        }
    }

    printf("Result: \n");
    for (i = 0; i <= k; i++)
        printf("%s ", words[i]);
}

Output:

RUN 1:
Enter string: Hello World
Result: 
olleH dlroW

RUN 2:
Enter string: Google Yahoo Bing
Result: 
elgooG oohaY gniB 

RUN 3:
Enter string: IncludeHelp.com
Result: 
moc.pleHedulcnI 

Explanation:

In the main() function, we created a string str and read the value of str from the user. Then we reverse each word of the string and print the result on the console screen.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C program to remove a given word from the string... >>
<< C program to reverse a string using recursion...