A C++ program to reverse each individual words in a sentence / string
#include <stdio.h>
#include <conio.h>
void reverse_string(char []);
void reverse_words(char []);
int main() {
char line[100];
puts("\n This is a c++ program to reverse words in a sentence \n ");
puts("\n Please enter a string having many words \n ");
gets(line);
reverse_words(line);
puts("\n Output after reversing each word of a given line : \n ");
puts(line);
getch();
return 0;
}
void reverse_words(char s[]) {
char word[100];
int k=0, j,i=0,m=0;
while(s[i]) { //processing complete string
while(s[k] != ' ' && s[k] != '\0') { //extracting one word from string
word[m] = s[k];
k++;
m++;
}
word[m] = '\0';
m = 0;
reverse_string(word); // reverse the extracted word
j = 0;
while (word[j]) { //copying the reversed word into original string
s[i] = word[j];
i++;
j++;
}
while (s[i] == ' ') // skipping space(s)
{ i++; }
k = i; // pointing to next word
}
}
void reverse_string(char str[])
{
int len, i=0;
char tmp;
while(str[i]) i++; // calculate length of string
len = i;
for (i = 0; i < len/2; i++)
{
tmp = str[i];
str[i] = str[len-1-i];
str[len-1-i] = tmp;
}
}
#include <conio.h>
void reverse_string(char []);
void reverse_words(char []);
int main() {
char line[100];
puts("\n This is a c++ program to reverse words in a sentence \n ");
puts("\n Please enter a string having many words \n ");
gets(line);
reverse_words(line);
puts("\n Output after reversing each word of a given line : \n ");
puts(line);
getch();
return 0;
}
void reverse_words(char s[]) {
char word[100];
int k=0, j,i=0,m=0;
while(s[i]) { //processing complete string
while(s[k] != ' ' && s[k] != '\0') { //extracting one word from string
word[m] = s[k];
k++;
m++;
}
word[m] = '\0';
m = 0;
reverse_string(word); // reverse the extracted word
j = 0;
while (word[j]) { //copying the reversed word into original string
s[i] = word[j];
i++;
j++;
}
while (s[i] == ' ') // skipping space(s)
{ i++; }
k = i; // pointing to next word
}
}
void reverse_string(char str[])
{
int len, i=0;
char tmp;
while(str[i]) i++; // calculate length of string
len = i;
for (i = 0; i < len/2; i++)
{
tmp = str[i];
str[i] = str[len-1-i];
str[len-1-i] = tmp;
}
}