[英]How would I store an empty string into a vector
我是C ++的新手,無法用定界符分割字符串並將子字符串放入向量中。
我的代碼如下:
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;
}
將字符串和定界符傳遞到函數中並執行拆分。 假定此函數將空字符串放入向量中,但對我而言不這樣做。
例如,如果我在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));
}
}
看來您的循環做得並不正確:您逐個字符地行走,在每次迭代中都start
一個start
前進。 我懷疑您實際上是想擁有一個當前位置,找到下一個定界符,將當前位置和定界符之間的字符串添加到結果中,並使當前位置成為定界符之后的字符:
for (std::string::size_type start(0); start != s.npos; )
{
std::string::size_type end(s.find_first_of(delim, start));
tokens.push_back(s.substr(start, end != s.npos? end - start: end));
start = end != s.npos? end + 1: s.npos;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.