Hi Guys,
i just wrote a program to print a sentence backwards using recursion. But i'm not too happy about it, if someone can give me a more optimized solution i'll be glad. You have to use std::string class.
input:
where the streets have no name
output:
name no have streets the where
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
// read a sentence and print it backwards using recursion
std::string mySentence(std::string);
int main()
{
std::string query;
std::cout << "enter a sentence" << std::endl;
if ( std::getline ( std::cin,query ) )
std::cout << mySentence(query) << std::endl;
}
std::string
mySentence(std::string sentence)
{
std::stringstream ss(sentence);
std::string token;
int wordCount = 0;
while(ss>>token)
{
wordCount++;
}
if(wordCount == 1)
return sentence;
int count = 0;
std::string::iterator it;
it = sentence.end();
while(*it != ' ')
{
it--;
count++;
}
int len = sentence.length();
int pos = len - count;
std::string subString = sentence.substr(0,pos);
return sentence.substr(pos) + mySentence(subString);
}