[英]Parse integers in string in C++
我有一个看起来像这样的字符串:
"{{2,3},{10,1},9}"
我想将其转换为字符串数组(或向量):
["{", "{", "2", "}", ",", "{", "10", ",", "1", "}", ",", "9", "}"]
我不能只拔出每个字符,因为某些整数可能是两位数,而且由于整数上有多个定界符(可能跟着或},所以我无法弄清楚如何使用stringstream。
只需遍历字符串即可。 如果我们在数字上,请走直到直到我们不在数字上:
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;
}
逻辑很简单:
遍历字符串。
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));
}
谢谢Sam和Barry的回答! 实际上,我想出了自己的解决方案(有时在此处发布问题可以使我更清楚地看到问题),但是您的解决方案更加优雅且与分隔符无关,我将进一步研究它们!
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.