gpt4 book ai didi

c++ - 我如何将空字符串存储到 vector 中

转载 作者:太空宇宙 更新时间:2023-11-04 12:12:35 24 4
gpt4 key购买 nike

我是 C++ 的新手,我在用定界符拆分字符串并将子字符串放入 vector 时遇到问题。

我的代码如下:

vector<string> split(const string &s, const string &delim)
{
string::size_type pos = s.find_first_of(delim,0);
int start = 0;
vector<string> tokens;

while(start < s.size())
{
if(start++ != pos + 1)
tokens.push_back(" ");
pos = s.find_first_of(delim, start);
tokens.push_back(s.substr(start, pos - start));
}

for(vector<string>::size_type i = 0; i != tokens.size(); ++i)
cout << tokens[i];

return tokens;
}

一个字符串和一个定界符被传递到函数中并执行拆分。这个函数应该将空字符串放入 vector 中,但我没有这样做。

例如,如果我将 main 中的函数调用为:

int main()
{
split("<ab><>cd<", "<>");
}

输出应该是

"","ab","","","","cd",""

减去引号

但是我的代码目前的输出是

ab b    cd d  

如有任何帮助,我们将不胜感激。

最佳答案

这就是诀窍......

#include <iostream>
#include <vector>

using namespace std;

vector<string> split(string record, string token) {
vector<string> results;
size_t startPos = 0;
size_t pos = 0;

// Step: If either argument is empty then return
// an empty vector.
if (record.length() == 0 || token.length() == 0) {
return results;
}

// Step: Go through the record and split up the data.
while(startPos < record.length()) {
pos = record.find(token, startPos);
if (pos == string::npos) {
break;
}

results.push_back(record.substr(startPos, pos - startPos));
startPos = pos + token.length();
}

// Step: Get the last (or only bit).
results.push_back(record.substr(startPos, record.length() - startPos));

// Step: Return the results of the split.
return results;
}

void printData(vector<string> list) {
for(vector<string>::iterator it = list.begin(); it < list.end(); it++) {
cout << *it << endl;
}
}

int main(int argc, char** argv) {
string record = "";
string delim = "";

if (argc == 3) {
record = argv[1];
delim = argv[2];
printData(split(record,delim));
} else {
string record = "comma,delimited,data";
string delim = ",";
printData(split(record,delim));

record = "One<--->Two<--->Three<--->Four";
delim = "<--->";
printData(split(record,delim));
}
}

关于c++ - 我如何将空字符串存储到 vector 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9221980/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com