我寫了一個函數,其百分比-字符串編碼,如下所示:更換
string percent_encode(string str)
{
string reserved =
// gen-delims
":/?#[]@"
// sub-delims
"!$&'()*+,;="
;
for(string::iterator i = str.begin(); i < str.end(); i++) {
int c = *i;
// replaces reserved, unreserved non-ascii and space characters.
if(c > 127 || c == 32 || reserved.find(*i) != string::npos) {
std::stringstream ss;
ss << std::hex << c;
str.replace(i, i + 1, "%" + ss.str());
}
}
return str;
}
當我調用該函數對於喜歡「一個& b」的一個字符串,一個out_of_range例外是拋出:
terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::replace
我用一個調試器跟蹤這個異常,看到替換工作得很好,但它迭代超出end();
這是我得到的,當我看迭代「我」:
{_M_current = 0x7fc43d61bd78 "a&b"}
{_M_current = 0x7fc43d61bd79 "&b"}
{_M_current = 0x7fc43d61bd7a "b"}
{_M_current = 0x7fc43d61bd7b ""}
{_M_current = 0x7fc43d61bd7c "o = a&b\n"}
{_M_current = 0x7fc43d61bd7d " = a&b\n"}
,然後嘗試更換「=」和失敗的out_of_range例外。 我不明白,迭代器如何明顯超越end()。
如果有人能解釋我,這是如何可能的,因爲我找不到網絡中有人遇到同樣的問題,我將不勝感激。
感謝和問候,
reeaal
編輯:
哎呀,我真的以爲複雜的。 x) 這就是我現在解決它的方法。
string percent_encode(string str)
{
string reserved =
// gen-delims
":/?#[]@"
// sub-delims
"!$&'()*+,;="
;
std::stringstream ss;
for(string::iterator i = str.begin(); i < str.end(); i++) {
// encodes reserved, unreserved non-ascii and space characters.
int c = *i;
if(c > 126 || c == 32 || reserved.find(*i) != string::npos) {
ss << '%' << std::hex << c;
} else {
ss << *i;
}
}
return ss.str();
}
感謝迭戈:)
恩......好主意,沒想過,謝謝。 :) – reeaal 2011-05-19 22:30:49
好的,你的解決方案的作品。它有一點點的開銷,因爲stringstream,但無論如何:) – 2011-05-19 22:44:08
你覺得怎麼樣? :)無論如何,我需要將其轉換爲十六進制表示。 – reeaal 2011-05-19 22:55:21