ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

C program to reverse every word of the given string

Here, we are going to learn how to reverse every word of the given string in C programming language?
Submitted by Nidhi, on July 17, 2021

Problem Solution:

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.

C String Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.