c++ - 从字符串中提取单个单词 C++

标签 c++ string vector

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

//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” ,然后在第二个循环之后,当我想要“你好”和“我的”时,“你好我的”。)我该如何解决这个问题?还有其他更好的方法可以从字符串中提取单个单词吗?我希望我没有混淆任何人。

最佳答案

参见 Split a string in 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,' ');

关于c++ - 从字符串中提取单个单词 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39050225/

相关文章:

c# - StartsWith Windows Server 2012 中的更改

c++ - C++ 中的 vector 、代理类和点运算符

c++ - 仅使用标准库创建 "Vector of References"的标准实践

c++ - 堆栈溢出后调用 SymSetOptions 时出现 AccessViolation

c++ - 函数内部的局部静态变量存储在哪里 - 在数据段中还是在堆栈中?

c++ - 使用迭代器从列表中打印结构值

c++ - 如何将带有 args 的成员函数作为参数传递给另一个成员函数?

python - Str 对象不可调用; Python 字典循环错误

c++ - 抛出错误 "as ‘p’ 中的包装函数未在此范围内声明”

c++ - 让用户创建自己的类实例