将字符串标记存储到数组中

Storing a string token into an array

本文关键字:数组 存储 字符串      更新时间:2023-10-16

我使用C++使用分隔符标记字符串,并且我可以在while循环中使用cout输出当前标记。我想做的是将令牌的当前值存储在一个数组中,以便以后可以访问它。这是我现在的代码:

string s = "Test>=Test>=Test";
string delimiter = ">=";
vector<string> Log;
int Count = 0;
size_t pos = 0;
string token;
while ((pos = s.find(delimiter)) != string::npos) {
token = s.substr(0, pos);
strcpy(Log[Count].c_str(), token.c_str());
Count++;
s.erase(0, pos + delimiter.length());
}

只需在向量上使用push_back。它将为您将令牌复制到向量中。无需计数;无需strcpy:

string s = "Test>=Test>=Test";
string delimiter = ">=";
vector<string> Log;
size_t pos = 0;
string token;
while ((pos = s.find(delimiter)) != string::npos) {
    token = s.substr(0, pos);
    Log.push_back(token);
    s.erase(0, pos + delimiter.length());
}

push_back()将满足您的需要。