4

My input is "Hello World" and my targeted output is "olleH dlroW".

So my idea is to get the sentence into a variable and then loop over the words in the sentence, reverse each of them and finally concatenate them into a new variable.

My question is: how to iterate over the words of the sentence?

#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;

string reverseword(string word)
{
    string rword;
    int size = word.length();
    while (size >= 0)
    {
        rword+= word[size];
        size = size -1;
    }   
    return rword;
}

int main()
{ 
    string sentence;
    cout<<"Enter the word/sentence to be reversed: ";
    cin >> sentence;
    string rsentence;
    // for every word in the sentence do
    {
        rword = reverseword(word);
        rsentence = rsentence + " " + rword; 
    }
    cout<<rword;
    return 0;
}
astudentofmaths
  • 1,122
  • 2
  • 19
  • 33

7 Answers7

6

Before you can iterate over words in a sentence, you need to read a sentence from input. This line

cin >> sentence;

reads the first word of a sentence, not the whole sentence. Use getline instead:

std::getline(std::cin, sentence);

With sentence in memory, you can iterate it word-by-word using istream_iterator as follows:

stringstream ss(sentence);
for (auto w = istream_iterator<string>(ss) ; w != istream_iterator<string>() ; w++) {
    string &word = *w;
    ...
}

Demo.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1
   for(short i=0;i<sentence.length();i++){

        if(sentence[i] == ' '){
            counter++;
            i++;
        }

        words[counter] += sentence[i];
    }

Note the above loop to split the sentence with space and store it to a string array, words[]

#include <iostream>
#include <stdio.h>
#include <string.h>

using namespace std;

string reverseword(string word) // function to reverse a word
{
    string rword;
    int size = word.length();
    while (size >= 0)
    {
        rword+= word[size];
        size = size -1;
    }   
    return rword;
}

int main()
{ 
    string sentence;

    cout << "Enter the word/sentence to be reversed: ";
    std::getline(std::cin, sentence);


    string rsentence;
    string words[100];


    string rword;

    short counter = 0;

    for(short i=0; i<sentence.length(); i++){ // looping till ' ' and adding each word to string array words

        if(sentence[i] == ' '){
            counter++;
            i++;
        }

        words[counter] += sentence[i];
    }



    for(int i = 0; i <= counter; i++) // calling reverse function for each words
    {
        rword = reverseword(words[i]);

        rsentence = rsentence + " " + rword;  // concatenating reversed words
    }

    cout << rsentence; // show reversed word

    return 0;
}

I have corrected the code. Hope this helps...!!

NB : You were using cin to read space seperated string that is not possible. You must use std::getline(std::cin, sentence) to read space separated strings.

You can also use std::reverse() to reverse a string

Chiel
  • 6,006
  • 2
  • 32
  • 57
Sreeram TP
  • 11,346
  • 7
  • 54
  • 108
  • Please use an `std::vector` rather than a stack allocated array. – Chiel Oct 15 '17 at 10:58
  • I guess it relates to my comment. C++ has containers that allow you to avoid the declaration of arrays like `words[100]`. This is unsafe and could lead to a segmentation fault. I suggest you edit it, as your answer has some nice elements. – Chiel Oct 15 '17 at 17:03
1

Here is a solution that uses find and reverse to achieve the output:

#include <iostream>
#include <string>
#include <algorithm>


int main() {
    std::string sentence;
    std::getline(std::cin, sentence);
    std::cout << sentence << std::endl;
    size_t cpos = 0;
    size_t npos = 0;
    while((npos = sentence.find(' ', cpos)) != std::string::npos)
    {
        std::reverse(sentence.begin() + cpos, sentence.begin() + npos);
        cpos = npos + 1;
    }
    std::reverse(sentence.begin() + cpos, sentence.end());
    std::cout << sentence << std::endl;
    return 0;
}

Input:

this is a nice day

Output:

this is a nice day
siht si a ecin yad
Support Ukraine
  • 42,271
  • 4
  • 38
  • 63
0

Please refer to Most elegant way to split a string? to split your sentence into tokens(words) then, iterate over the new list of words to perform any operation

Muhannad A.Alhariri
  • 3,702
  • 4
  • 30
  • 46
0

An answers above gives a way to convert your input to words, i.e., cin >> sentence returns a "word" (so, just call it repeatedly).

However, this brings up the question of what is a "word". You would like to translate a computer construct - string of characters - into a more complex form - words. So, you must define what you mean when you want words. It can be as simple as "space" separated substrings or your string - then use the split function, or read your string a word at a time (cin >> word)

Or you may have more stringent requirements, like they can't include punctuation (like a period at the end of a sentence) or numbers. Then think about using Regex and word patterns (like, "\w+").

Or you may want "real" words like you would find in a dictionary. Then you need to take into account your locale, parse your input into chunks (using split, Regex, or something), and look up each chunk in a human language dictionary.

In other words, "word" parsing is only as simple or complex as your requirements are.

Les
  • 10,335
  • 4
  • 40
  • 60
0

With Boost you could use the boost::split function:

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <boost/algorithm/string.hpp>

int main()
{
    std::string sentence = "Hello world";

    std::vector<std::string> words;
    boost::split(words, sentence, boost::is_any_of(" "));

    std::string rsentence;
    for (std::string word : words) // Iterate by value to keep the original data.
    {
        std::reverse(word.begin(), word.end());
        rsentence += word + " "; // Add the separator again.
    }
    boost::trim(rsentence); // Remove the last space.

    std::cout << rsentence << std::endl;

    return 0;
}
Chiel
  • 6,006
  • 2
  • 32
  • 57
-1

This answer is my humble contribution to the fight against global warming.

#include <string>                                                            
#include <iostream>                                                          
#include <algorithm>                                                         
#include <cctype>                                                            

int main()                                                                   
{                                                                            
    std::string sentence;                                                    
    while (std::getline(std::cin, sentence))                                 
    {                                                                        
        auto ws = sentence.begin();                                          

        while (ws != sentence.end())                                         
        {                                                                    
            while (std::isspace(*ws)) ++ws;                                  
            auto we = ws;                                                    
            while (we != sentence.end() && !std::isspace(*we)) ++we;         
            std::reverse(ws, we);                                            
            ws = we;                                                         
        }                                                                    
        std::cout << sentence << "\n";                                       
    }                                                                        
}

This assumes "word" is defined as "a sequence of non-whitespace characters". It is easy to substitute a different character class instead of "non-whitespace", e.g. for alphanumeric characters use std::isalnum. A definition that reflects the real-world notion of word as e.g. used in natural language sciences is far far beyond the scope of this answer.

n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243