我正在阅读一本编码面试书,却被困在一个问题上:用'%20'替换字符串中的所有空格。
我尝试在我的编译器中运行这个解决方案,但是得到了这个错误: Subscript超出了范围。因此,我查找了该错误的堆栈溢出,并得到了一个解决方案,尝试用+=追加新字符,而不是仅仅将新字符分配给字符串,但仍然会产生相同的错误。
这是我的密码。非常感谢你的时间!
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;
}发布于 2015-08-21 08:48:13
您没有调整字符串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在调整其大小之前,必须按照原来字符串的大小进行初始化。
发布于 2015-08-21 09:46:32
如果您正在寻找一种实用的解决方案,而不过分关注性能,那么以下是一些简单得多的方法:
void replaceSpaces(string &str) {
str = std::regex_replace(str, std::regex(" "), "%20");
}发布于 2015-08-21 09:47:20
这个怎么样?
#include <iostream>
#include <string>
std::string replaceSpaces(std::string str)
{
std::string newStr;
for (char c : str)
{
if (c == ' ')
newStr.append("%20");
else
newStr.push_back(c);
}
return newStr;
}
int main()
{
std::string test = "sophisticated ignorance, write my curses in cursive";
std::string newtest = replaceSpaces(test);
std::cout << test << std::endl << newtest << std::endl;
}https://stackoverflow.com/questions/32135988
复制相似问题