我有一个看起来像这样的字符串:
"{{2,3},{10,1},9}"
我希望将其转换为字符串的数组(或向量):
["{", "{", "2", "}", ",", "{", "10", ",", "1", "}", ",", "9", "}"]
我不能单独拉出每个字符,因为有些整数可能是两位数,我无法弄清楚如何使用stringstream,因为整数上有多个分隔符(可以跟着,或者})
答案 0 :(得分:3)
走完绳子。如果我们在一个数字上,那就走吧,直到我们不在数字上:
std::vector<std::string> split(std::string const& s)
{
std::vector<std::string> results;
std::locale loc{};
for (auto it = s.begin(); it != s.end(); )
{
if (std::isdigit(*it, loc)) {
auto next = std::find_if(it+1, s.end(), [&](char c){
return !std::isdigit(c, loc);
});
results.emplace_back(it, next);
it = next;
}
else {
results.emplace_back(1, *it);
++it;
}
}
return results;
}
答案 1 :(得分:0)
逻辑很简单:
迭代字符串。
push_back()
每个字符作为它自己的字符串输入到输出向量中,除非它是一个数字而最后一个字符是一个数字,在这种情况下将数字附加到最后一个字符串中输出向量:
那就是它。
std::string s="{{2,3},{10,1},9}";
std::vector<std::string> v;
bool last_character_was_a_digit=false;
for (auto c:s)
{
if ( c >= '0' && c <= '9')
{
if (last_character_was_a_digit)
{
v.back().push_back(c);
continue;
}
last_character_was_a_digit=true;
}
else
{
last_character_was_a_digit=false;
}
v.push_back(std::string(&c, 1));
}
答案 2 :(得分:-1)
std::vector<std::string> myVector;
std::string nextSubStr;
for (int i=0; i<myString.size(); i++)
{
nextSubStr = myString[i];
// if we pulled a single-digit integer out of myString
if (nextSubStr != "{" && nextSubStr != "}" && nextSubStr != ",")
{
// let's make sure we get the whole integer!
int j=i;
peekNext = myString[++j];
while (peekNext != "{" && peekNext != "}" && peekNext != ",")
{
// another digit on the integer
nextSubStr += peekNext;
peekNext = myString[++j];
i++;
}
}
myVector.push_back(nextSubStr);
}