我试图制作一个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;
}
}
Run Code Online (Sandbox Code Playgroud)
但是,这仅适用于字符串中遇到的第一个空格。如果单词之前有任何空格(例如,如果我们有“ Hello my World”,则在第一个循环之后,pushBackVar将为“ Hello”)将不起作用。当我想要“ Hello”和“ my”时,在第二个循环后单击“ Hello my”。)如何解决此问题?还有其他更好的方法来从字符串中提取单个单词吗?我希望我不会混淆任何人。
小智 5
请参阅在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;
}
Run Code Online (Sandbox Code Playgroud)
因此,就您而言:
words = split(temp,' ');
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18408 次 |
| 最近记录: |