gpt4 book ai didi

c++ - 在此字符串操作代码中出现 out_of_range 错误

转载 作者:行者123 更新时间:2023-11-28 08:02:15 25 4
gpt4 key购买 nike

嗨,我正在点击 std::out_of_range: basic_string::substr在下面的代码中。一直在努力修复它,但无法完成。

std::string orig_str = "1-1,2-3,4-4,56-75,77-77";
size_t number_digits;
for (size_t i = 0; i < orig_str.size(); ++i)
{
number_digits = orig_str.find_first_of(",", i) - i - 1;
if(orig_str.find("-", i) != std::string::npos)
if (orig_str.substr(i - number_digits, i - 1) == orig_str.substr(i + 1, i + number_digits))
orig_str.erase(i-number_digits, number_digits + 1);
}

基本上这段代码是通过操作字符串来移除一些范围预期行为是:输入字符串: "0-0,2-7,88-88"输出字符串: "0,2-7,88"

最佳答案

AJ,这是我们在聊天中讨论的伪代码:

input_string = "1-1,2-3,4-4,56-75,77-77"
output_string = ""
while (input_string is not empty)
sub = input_string.substr(up to first comma)
input_string = input_string.substr(after first comma)
if (sub.substr(up to dash) == sub.substr(after dash))
output_string += sub.substr(up to dash)
else
output_string += sub
if (input_string is not empty)
output_string += ","

关于c++ - 在此字符串操作代码中出现 out_of_range 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11113050/

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