从字符串c ++中提取单个单词 [英] extract individual words from string c++

查看:27
本文介绍了从字符串c ++中提取单个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to make a C++ program that receives user input, and extracts the individual words in the string, e.g. "Hello to Bob" would get "Hello", "to", "Bob". Eventually, I will be pushing these into a string vector. This is the format I tried to use when designing the code:

//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"时.)我该如何解决这个问题?还有其他更好的方法可以从字符串中提取单个单词吗?我希望我没有混淆任何人.

However, this only works for the first space encountered in the string.It does not work if there are any spaces before the word (e.g. if we have "Hello my World", pushBackVar will be "Hello" after the first loop, and then "Hello my" after the second loop, when I want "Hello" and "my".) How do I fix this? Is there any other better way to extract individual words from a string? I hope I haven't confused anyone.

推荐答案

参见 拆分字符串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 ++中提取单个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆