c++ - 用 '%20' 替换字符串中的所有空格 (C++)

标签 c++ string memory-management str-replace

在理解部分代码时遇到一些困难;我得到的输出也是错误的。问题是用“%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/

相关文章:

c++ - 为什么这个程序的输出是意外的?

c++ - 用 C/C++ 中的地址调用 lua 函数?

c++ - 如何在汇编级别分析 C++ 函数?

c++ - 查询相似句子的有效方法

C++ -- 智能指针和自定义内存分配困境

c++ - 在另一个类中创建对象(无继承)

string - 压缩特里实现?

c++ - 用另一个子字符串 C++ 替换子字符串

c++ - 当内存限制接近时转储缓冲数据

javascript - 跟踪javascript中的内存使用情况