在理解部分代码时遇到一些困难;我得到的输出也是错误的。问题是用“%20”替换字符串中的所有空格。完整代码如下所示;它可以编译但不能完全按预期运行。
#include <iostream>
#include <string>
using namespace std;
void replaceSpaces(string str){
//Getting the length of the string, counting the number of spaces
int strLen = str.length();
int i, count = 0;
for (i = 0; i <= strLen; i++) {
if(str[i]==' ')
count++;
}
//Determining the new length needed to allocate for replacement characters '%20'
int newLength = strLen + count * 2;
str[newLength] = '\0';
for (i = strLen - 1; i >= 0; i--) {
if (str[i] == ' ') {
str[newLength - 1] = '0';
str[newLength - 2] = '2';
str[newLength - 3] = '%';
newLength = newLength - 3;
}
else {
str[newLength - 1] = str[i];
newLength = newLength -1;
}
}
cout << str <<endl;
}
int main() {
string str = "hello jellybean hello";
replaceSpaces(str);
return 0;
}
我可能遗漏了一些明显的东西,但是在这一行中分配新的字符串长度时:
int newLength = strLen + count * 2;
此处我们将空格数乘以 2,但如果我们试图用“%20”替换所有空格,为什么不将其乘以 3?
str[newLength] = '\0';
此行是否表示字符串中最后一个字符之后的位置分配了一个空空格?
我也对 else
语句感到困惑。
else {
str[newLength - 1] = str[i];
newLength = newLength -1;
}
不确定我是否完全了解执行此操作的情况。
函数编译运行时,如果
string str = "你好糖 bean 你好";
预期的输出将是 hello%20jellybean%20hello,除了我得到的输出是 hello%20jellybean%20h。
在时间复杂度上,由于有两个独立的for
循环,时间复杂度是O(n)吗?
我知道我问了很多不同的问题,非常感谢您的回答!
最佳答案
这是错误的:
str[newLength] = '\0';
std::string
对象根据其大小在内部维护其 NUL 终止符。你要
str.resize(newLength);
相反。
关于c++ - 用 '%20' 替换字符串中的所有空格 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38362837/