提取C++字符串中的单词

6

我正在尝试制作一个C++程序,它可以接收用户输入,并提取字符串中的单词,例如,“Hello to Bob”将得到“Hello”,“to”,“Bob”。最终,我将把它们推入一个字符串向量中。这是我在设计代码时尝试使用的格式:

//string libraries and all other appropriate libraries have been included above here
string UserInput;
getline(cin,UserInput)
vector<string> words;
string temp=UserInput;
string pushBackVar;//this will eventually be used to pushback words into a vector
for (int i=0;i<UserInput.length();i++)
{
  if(UserInput[i]==32)
  {
    pushBackVar=temp.erase(i,UserInput.length()-i);
    //something like words.pushback(pushBackVar) will go here;
  }  
}

然而,这仅适用于字符串中遇到的第一个空格。如果单词前有空格(例如,如果我们有“Hello my World”),则它不起作用。在第一次循环后,pushBackVar将是“Hello”,在第二次循环后,它将变为“Hello my”,但我想要的是“Hello”和“my”。如何解决这个问题?是否有其他更好的方法从字符串中提取单词?我希望没有让任何人感到困惑。

1
可能是在C++中分割字符串的重复问题? - Sebastian Lenartowicz
4个回答

9

参考C++中如何分割字符串?

#include <string>
#include <sstream>
#include <vector>

using namespace std;

void split(const string &s, char delim, vector<string> &elems) {
    stringstream ss(s);
    string item;
    while (getline(ss, item, delim)) {
        elems.push_back(item);
    }
}


vector<string> split(const string &s, char delim) {
    vector<string> elems;
    split(s, delim, elems);
    return elems;
}

所以在你的情况下,只需执行以下操作:
words = split(temp,' ');

你可能应该引用它,但我不确定。 - Rakete1111

3

您可以直接使用运算符 >> 将单词从微缓冲区(字符串)中提取出来。不需要使用getline函数。请查看下面的函数:

vector<string> Extract(const string& Text) {
    vector<string> Words;
    stringstream ss(Text);
    string Buf;

    while (ss >> Buf)
        Words.push_back(Buf);

    return Words;
}

1
#include <algorithm>        // std::(copy)
#include <iostream>         // std::(cin, cout)
#include <iterator>         // std::(istream_iterator, back_inserter)
#include <sstream>          // std::(istringstream)
#include <string>           // std::(string)
#include <vector>           // std::(vector)
using namespace std;

auto main()
    -> int
{
    string user_input;
    getline( cin, user_input );
    vector<string> words;
    {
        istringstream input_as_stream( user_input );
        copy(
            istream_iterator<string>( input_as_stream ),
            istream_iterator<string>(),
            back_inserter( words )
            );
    }

    for( string const& word : words )
    {
        cout << word << '\n';
    }
}

0

在这里,我从句子中创建了一个单词向量。

#include<bits/stdc++.h>
using namespace std;
int main(){
string s = "the devil in the s";
string word;
vector<string> v;
for(int i=0; i<s.length(); i++){
    if(s[i]!=' '){
        word+=s[i];
    }
    else{
        v.push_back(word);
        if(i<s.length()+1)
            word.clear();
    }  
}
v.push_back(word);
for(auto i:v){
    cout<<i<<endl;
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接