【问题标题】:How to split a sentence of any length into words and store them into variables c++如何将任意长度的句子拆分为单词并将它们存储到变量c ++中
【发布时间】:2023-03-24 04:50:01
【问题描述】:

我需要一些帮助来制作一个将句子分成单词的函数,这个函数应该适用于不同长度的句子。

这里是示例代码:

void spilt_sentence(string sentence)
{}
int main()
{
   std::string sentence1= "Hello everyone";
   std::string sentence2= "Hello I am doing stuff";
   split_sentence(sentence1);
   split_sentence(sentence2);
   return 0;
}

我看到有人使用 std::istringstream 来获取每个空格之前的每个单词,但我真的不知道它是如何工作的。当我输入 std::istringstream ss(sentence); 时,它给了我错误在代码中。另外,我正在使用 c++98 并使用 cygwin 编译我的程序。有什么线索吗?谢谢。

编辑:该函数将根据句子中有多少单词创建许多变量。

编辑:我实际上正在开发一个 LinkedList 程序,我在这里要做的是将句子拆分为单词,然后生成包含每个单词的新节点。

这是实际代码(注意:我对其进行了一些修改,因此它与我的实际代码不完全相同。而且我没有为 Node 使用结构),假设第 1 句是“大家好”,第 2 句是“你好,我在做事”。

The expected output will be:
linkedlist1:
"hello"<->"everyone"
linkedlist2:
"hello"<->"I"<->"am"<->"doing"<->"stuff"

LinkedList.cpp 内:

void LinkedList::add(std::string sentence)
{
   //breaks down the sentence into words
   std::istringstream ss(sentence);
   do
   {
       std::string word;
       ss >> word;

       //store them in nodes in a linkedlist
       Node* new_tail = new Node(word);
       if (size == 0)
       {
           head = new_tail;
           tail = new_tail;
       }
       else
       {
           new_tail->set_previous(tail);
           tail->set_next(new_tail);
           tail = new_tail;
       }
       new_tail = NULL;
       size++;

   }
   while(ss);
}

[已修复]编译时弹出错误消息,说 std::istringstream ss 有默认设置但类型不完整。我该怎么办?

error

【问题讨论】:

标签: c++ split c++98


【解决方案1】:

这里是使用流的函数,这个函数只对向量起作用,你不能对数组使用这个函数,但是如果你愿意,你可以为你修改它。 这是代码和使用示例

#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <iostream>
using namespace std;

void split_sentence(const string& str, vector<string>& cont)
{
    istringstream iss(str);
    copy(istream_iterator<string>(iss),
         istream_iterator<string>(),
         back_inserter(cont));


     //checking for punctuation marks and if found, we remove them from the word
     for(int i = 0, sz = cont.size(); i < sz; i++){
        string word = cont.at(i);
        for(int j = 0, len = word.length(); j < len; j++){
            if(ispunct(word[j])){
                cont.at(i) = word.substr(0, word.length() - 1);
            }
        }
     }
}

int main(){

    string sentence = "this is a test sentence for stackoverflow!";
    vector<string> words;

    split_sentence(sentence, words);

    for(int i = 0, sz = words.size(); i < sz; i++){
        cout<<words.at(i) << endl;
    }

    return 0;

}

这是输出

this
is
a
test
sentence
for
stackoverflow

如果您还想打印标点符号,请删除函数中的双 for 循环。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-30
    相关资源
    最近更新 更多