简体   繁体   English

如何在C ++中迭代句子的单词?

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

My input is "Hello World" and my targeted output is "olleH dlroW". 我的输入是“Hello World”,我的目标输出是“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: 改为使用getline

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

With sentence in memory, you can iterate it word-by-word using istream_iterator as follows: 使用内存中的sentence ,您可以使用istream_iterator逐字迭代它,如下所示:

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[] 注意上面的循环用空格分割句子并将其存储到字符串数组, 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. 注意:您使用cin来读取空间分隔的字符串,这是不可能的。 You must use std::getline(std::cin, sentence) to read space separated strings. 您必须使用std::getline(std::cin, sentence)来读取空格分隔的字符串。

You can also use std::reverse() to reverse a string 您还可以使用std::reverse()来反转字符串

Here is a solution that uses find and reverse to achieve the output: 这是一个使用findreverse来实现输出的解决方案:

#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). 上面的答案提供了一种将输入转换为单词的方法,即cin >> sentence返回一个“单词”(因此,只需重复调用它)。

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 ) 它可以像“空格”分隔的子串或你的字符串一样简单 - 然后使用split函数,或者一次一个字地读取你的字符串( 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+"). 然后考虑使用正则表达式和单词模式(如“\\ 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. 然后,您需要考虑您的语言环境,将您的输入解析为块(使用split,Regex或其他东西),并在人类语言词典中查找每个块。

In other words, "word" parsing is only as simple or complex as your requirements are. 换句话说,“单词”解析只是与您的要求一样简单或复杂。

With Boost you could use the boost::split function: 使用Boost,您可以使用boost::split函数:

#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 . 很容易替换不同的字符类而不是“非空格”,例如对于字母数字字符使用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. 反映现实世界的单词概念的定义,例如在自然语言科学中使用的远远超出了这个答案的范围。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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