我正在阅读一本编程面试书,但遇到了一个问题:用“%20”替换字符串中的所有空格。
我尝试在我的编译器中运行这个解决方案,但出现了这个错误:字符串下标超出范围。因此,我在 stackoverflow 中查找了该错误,并找到了一个解决方案来尝试使用 += 附加新字符,而不是仅仅将新字符分配给字符串,但这仍然会产生相同的错误。
这是我的代码。非常感谢您的宝贵时间!
void replaceSpaces(string &str)
{
int spaces = 0;
// Count number of spaces in original string
for (int i = 0; i < str.size(); i++)
{
if (str[i] == ' ')
spaces++;
}
// Calculate new string size
int newSize = str.size() + (2 * spaces);
str.resize(newSize); // thanks Vlad from Moscow
// Copy the chars backwards and insert '%20' where needed
for (int i = str.size() - 1; i >= 0; i--)
{
if (str[i] == ' ')
{
str[newSize - 1] = '0'; // += '0' didnt work
str[newSize - 2] = '2'; // += didnt work
str[newSize - 3] = '%'; // same
newSize = newSize - 3;
}
else
{
str[newSize - 1] = str[i]; // same
newSize--;
}
}
}
int main()
{
string test = "sophisticated ignorance, write my curses in cursive";
replaceSpaces(test);
cout << test << endl;
}
最佳答案
您没有调整字符串 str
的大小。
您设置变量 newSize
int newSize = str.size() + (2 * spaces);
大于 str.size()
并像 str
中的索引一样使用它
str[newSize - 1] = str[i];
至少你一开始会写
str.resize( newSize );
这是一个演示程序,展示了如何编写该函数
#include <iostream>
#include <string>
std::string & replaceSpaces( std::string &s )
{
std::string::size_type spaces = 0;
// Count number of spaces in original string
for ( char c : s ) if ( c == ' ' ) ++spaces;
if ( spaces != 0 )
{
auto i = s.size();
// Calculate new string size
auto j = s.size() + 2 * spaces;
s.resize( j );
// Copy the chars backwards and insert '%20' where needed
while ( i != j )
{
if ( s[--i] == ' ' )
{
s[--j] = '0';
s[--j] = '2';
s[--j] = '%';
}
else
{
s[--j] = s[i];
}
}
}
return s;
}
int main()
{
std::string test = "sophisticated ignorance, write my curses in cursive";
std::cout << "\"" << test << "\"\n";
std::cout << "\"" << replaceSpaces( test ) << "\"\n";
}
程序输出为
"sophisticated ignorance, write my curses in cursive"
"sophisticated%20ignorance,%20write%20my%20curses%20in%20cursive"
编辑:按照我的建议在循环中插入带有 resize
的语句之后
for (int i = str.size() - 1; i >= 0; i--)
^^^^^^^^^^^^^^^^^^^^^^
变量 i
必须使用调整大小之前字符串的旧大小进行初始化。
关于c++ - 用 "%20"替换空格 - 字符串下标超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32135988/