简体   繁体   中英

How to iterate over the words of a sentence in C++?

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;
}

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.

   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

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

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

An answers above gives a way to convert your input to words, ie, 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.

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;
}

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", eg for alphanumeric characters use std::isalnum . A definition that reflects the real-world notion of word as eg used in natural language sciences is far far beyond the scope of this answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM