div*_*hch 13 c++ string system-calls strtok
我试图将一个字符串分成多个字符串,以制作一个自定义的终端.到目前为止,我一直在使用strtok分离控制信号,但是我不明白如何分离角色的特定实例.例如:
string input = "false || echo \"hello world\" | grep hello";
当试图strtok这个input并试图分开使用|输出将是:
false ,echo "hello world" , grep hello
相反,我希望输出为:
false || echo "hello world" , grep hello
怎样才可以有函数strtok治疗|和||不同的,而不是它说他们是一样的吗?
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
vector<string> split(string sentence,char delim)
{
string tempSentence = "";
tempSentence += delim;
tempSentence += sentence;
tempSentence += delim;
string token;
vector<string> tokens;
for (int i=1;i<tempSentence.length()-1;++i)
{
if (tempSentence[i] == delim && tempSentence[i-1] != delim && tempSentence[i+1] != delim)
{
if (token.length()) tokens.push_back(token);
token.clear();
}
else
{
token += tempSentence[i];
}
}
if (token.length()) tokens.push_back(token);
return tokens;
}
int main() {
string sentence = "false || echo \"hello world\" | grep hello";
char delim='|';
vector<string> tokens = split(sentence,delim);
for_each(tokens.begin(), tokens.end(), [&](string t) {
cout << t << endl;
});
}
Run Code Online (Sandbox Code Playgroud)
难看又长!但有效!