gpt4 book ai didi

c++ - 如何提取和删除 std::string 中的字符

转载 作者:行者123 更新时间:2023-11-27 23:14:53 25 4
gpt4 key购买 nike

假设我有这种字符串格式:

"<RGB:255,0,0>this text is colored RED.<RGB:0,255,0> While this text is colored GREEN";

我想提取 <RGB> 中的值即 255,0,0 并将其放在其他变量上,然后删除 char来自 '<''>' .

到目前为止我的代码:

//this function is called after the loop that checks for the existence of '<'

void RGB_ExtractAndDelete(std::string& RGBformat, int index, RGB& rgb)
{
int i = index + 5; //we are now next to character ':'
std::string value;
int toNumber;

while (RGBformat[i] != ',')
{
value += RGBformat[i++];
}
++i;
std::stringstream(value) >> toNumber;
rgb.R = toNumber;
value = "";

while (RGBformat[i] != ',')
{
value += RGBformat[i++];
}
++i;
std::stringstream(value) >> toNumber;
value = "";
rgb.G = toNumber;

while (RGBformat[i] != '>')
{
value += RGBformat[i++];
}
++i;
std::stringstream(value) >> toNumber;
value = "";
rgb.B = toNumber;

//I got the right result here which is
//start: <, end: >
printf("start: %c, end: %c\n", RGBformat[index], RGBformat[i]);
//but fail in this one
//this one should erase from '<' until it finds '>'
RGBformat.erase(index, i);

}

如果我把 <RGB:?,?,?>在字符串的开头,它可以工作,但是当它在非“<”字符旁边找到它时会失败。或者你能建议更好的方法来做到这一点吗?

最佳答案

  1. 使用std::str::find找到 <RGB , : , ,> .
  2. 使用std::str::substr “剪掉”字符串。
  3. 添加if (!std::strinstream(value)>> toNumber) ...检查该号码是否实际被接受。

像这样:

std::string::size_type index = std::RGBformat.find("<RGB");
if (index == std::string::npos)
{
... no "<RGB" found
}
std::string::size_type endAngle = std::RGBformat::find(">", index);
if (endAngle == std::string::npos)
{
... no ">" found...
}
std::string::size_type comma = std::RGBformat.find(",", index);
if (comma == std::string::npos && comma < endAngle)
{
... no "," found ...
}
std::string value = RGBformat.substr(index, comma-index-1);
std::stringstream(value) >> toNumber;
value = "";
rgb.R = toNumber;

std::string::size_type comma2 = std::RGBformat.find(",", comma+1);
if (comma2 == std::string::npos && comma2 < endAngle)
...

请注意,这可能看起来比您当前的代码有点笨拙,但它的优点是更加安全。如果有人传入 "<RGB:55> .... "对于您现有的代码,它会中断,因为它会一直运行,直到您感到无聊并按下一个键来停止它,或者它崩溃,以先到者为准...

关于c++ - 如何提取和删除 std::string 中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17039478/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com