簡體   English   中英

如何在C ++中迭代句子的單詞?

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

我的輸入是“Hello World”,我的目標輸出是“olleH dlroW”。

所以我的想法是將句子放入變量然后循環句子中的單詞,反轉它們中的每一個,最后將它們連接成一個新變量。

我的問題是:如何迭代句子的單詞?

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

在迭代句子中的單詞之前,您需要從輸入中讀取一個句子。 這條線

cin >> sentence;

讀取句子的第一個單詞,而不是整個句子。 改為使用getline

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

使用內存中的sentence ,您可以使用istream_iterator逐字迭代它,如下所示:

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

演示。

   for(short i=0;i<sentence.length();i++){

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

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

注意上面的循環用空格分割句子並將其存儲到字符串數組, 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;
}

我已經糾正了代碼。 希望這可以幫助...!!

注意:您使用cin來讀取空間分隔的字符串,這是不可能的。 您必須使用std::getline(std::cin, sentence)來讀取空格分隔的字符串。

您還可以使用std::reverse()來反轉字符串

這是一個使用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;
}

輸入:

this is a nice day

輸出:

this is a nice day
siht si a ecin yad

請參考最優雅的方式分割字符串? 然后,將句子分成標記(單詞),迭代新的單詞列表以執行任何操作

上面的答案提供了一種將輸入轉換為單詞的方法,即cin >> sentence返回一個“單詞”(因此,只需重復調用它)。

然而,這提出了什么是“單詞”的問題。 您希望將計算機構造(字符串)轉換為更復雜的形式 - 單詞。 所以,你必須在你想要的時候定義你的意思。 它可以像“空格”分隔的子串或你的字符串一樣簡單 - 然后使用split函數,或者一次一個字地讀取你的字符串( cin >> word

或者您可能有更嚴格的要求,例如它們不能包括標點符號(如句子末尾的句號)或數字。 然后考慮使用正則表達式和單詞模式(如“\\ w +”)。

或者你可能想要在字典中找到的“真實”單詞。 然后,您需要考慮您的語言環境,將您的輸入解析為塊(使用split,Regex或其他東西),並在人類語言詞典中查找每個塊。

換句話說,“單詞”解析只是與您的要求一樣簡單或復雜。

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

這個答案是我對抗全球變暖的謙卑貢獻。

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

這假設“單詞”被定義為“一系列非空白字符”。 很容易替換不同的字符類而不是“非空格”,例如對於字母數字字符使用std::isalnum 反映現實世界的單詞概念的定義,例如在自然語言科學中使用的遠遠超出了這個答案的范圍。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM