Home »
C programs »
C string programs
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 »