如何将空字符串存储到向量中
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
。我怀疑您实际上想要一个当前位置,找到下一个分隔符,将当前位置和分隔符之间的字符串添加到结果中,并使当前位置成为分隔符之后的字符:
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;
}
相关文章:
- 访问存储在向量C++中的结构的多态成员
- 添加存储在向量中的大整数的函数出现问题
- 在 std::无符号字符的向量处存储 int 的十六进制表示形式
- 如何从用户那里获取输入并将其存储在向量中?
- 如何从文件中读取两个字符串和数字数组,并将它们存储在对象向量中
- 将无符号字符的向量存储在数组中会给我 std::bad_alloc
- 在二维向量或数组中可以存储的最大元素数是多少?
- 存储在堆分配向量中的指针的免费存储
- 将相同共享指针的副本存储在不同的向量中是否是一种好的做法?
- 将数组信息存储到 c++ 向量中有一个"Access violation reading location"
- Sqlite3:将数据库表名存储在向量中
- 如何在数组和向量 c++ 中存储和保存输入
- C++ 将抽象类型的动态分配对象传递给函数并存储在向量中
- 代码将向量存储为向量<vector>,为什么没有错误消息?
- 替代STD ::向量存储参考而不是对象的副本
- 将向量存储在<file> CStringArray 中?
- 将可变大小结构的向量存储在c++中的二进制文件中
- 使用向量c++存储和洗牌一副牌
- 将指针向量存储在文件中并再次读取它们
- 是否可以/建议将向量存储在结构中?C++