09/11/2015

C++ Program To Reverse a Sentence or String

Problem:- Write A C++ Program To Print Reverse Sentence or reverse a string in c++ program or how to reverse a string in c++ using functions or reverse a string in c++ using for loops or reverse string in c++ without using a function or how to reverse a string in c++ using strrev or Reversing a string in c using a while loop or C++ Program to Reverse a String or C program to reverse a given number using do..while loop or c++ program to reverse a string using for loop or C++ Program To Reverse a Sentence or String.

Check This:- Hacker rank solution for Strings, Classes, STL, Inheritance in C++.

Logic:- Like reverse string, this is a reverse sentence. So first we are taking an input from the user after that we are finding the string or sentence last index point so we can reverse a sentence while reversing a sentence if any space occurs we take and space and print space after that again string starts printing. I  strongly prefer a program first try to understand this program so can understand the logic basically what is going on. Check C Program For Reverse A String Without (srtrev) Using Library Function. Now try by yourself if you are getting problem Comment Below and also sure that you have read the full post.


Also Check:- Geeksforgeeks solution for School, Basic, Easy, Medium, Hard in C++.

Extreme Recommended:- Like our Facebook Page or Join our Facebook Group and Google plus Community for up-to-date for a new post or if you have any Query you can ask there with lots of coders also suggest to your Friends to join and like our page.


Solution:-


#include<iostream>
#include<cstdio>
using namespace std;
int main()
{

/*Visit - www.programmingwithbasics.com*/
   
    cout<<"=====================================";
    cout<<"\nVisit - www.programmingwithbasics.com";
    cout<<"\n=====================================";
    
  int i, prev, next, j, k;
  //prev=0;
  char st[100];

  cout<<"\n\nEnter The Sentence: ";
  gets(st);

  for(i=0;st[i]!='\0';i++) 
  prev=i;

  cout<<"\n\nSentence In Reverse Order Is As Follow \n\n";
  for(k=i-1;k>=0;k--)
 
    if(st[k]==' '||k==0)
    {
    if(k==0)
    {
    next=0;
}
    else
    {
    next=k+1;
}
   
    for(j=next;j<=prev;j++)
    {
    cout<<st[j];
    }
cout<<" ";
    prev=next-2;  
    }
  }

  return 0;
}

Output:-



Previous Post
Next Post

post written by:

Hi, I’m Ghanendra Yadav, SEO Expert, Professional Blogger, Programmer, and UI Developer. Get a Solution of More Than 500+ Programming Problems, and Practice All Programs in C, C++, and Java Languages. Get a Competitive Website Solution also Ie. Hackerrank Solutions and Geeksforgeeks Solutions. If You Are Interested to Learn a C Programming Language and You Don't Have Experience in Any Programming, You Should Start with a C Programming Language, Read: List of Format Specifiers in C.
Follow Me

0 Comments: