用“%20”替换字符串中的所有空格 (C++)

Replacing all spaces in a string with '%20' (C++)

在理解部分代码时遇到一些困难;我得到的输出也是错误的。问题是将字符串中的所有 space 替换为“%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] = '[=10=]';
    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;

此处我们将 space 的数量乘以 2,但是如果我们试图用“%20”替换所有 space,为什么不将其乘以 3?


str[newLength] = '[=13=]';

此行是否表示字符串中最后一个字符之后的位置被分配了空 space?


我也对 else 声明感到困惑。

 else {
        str[newLength - 1] = str[i];
        newLength = newLength -1;
    }

不确定我是否完全了解执行此操作的情况。


函数编译时运行,如果

string str = "hello jellybean hello";

预期的输出将是 hello%20jellybean%20hello,但我得到的输出是 hello%20jellybean%20h

在时间复杂度上,由于有两个独立的for循环,时间复杂度会不会是O(n)

我知道我问了很多不同的问题,非常感谢您的回答!

int newLength = strLen + count * 2;

说分配space(后面),等于字符串的长度,加上找到的白色space的个数乘以2,有道理

例如:so glad to help,应该使用白人 space 居住的插槽用于 %,并且他们每个人还需要两个插槽,用于 [=14] =] 将发挥作用的替换部分。


这是错误的

str[newLength] = '[=11=]';

你看不出来吗?您访问超出字符串范围的内存。你表现得好像你实际上分配了 space 等于 newLength,但你还没有在代码中的任何地方。

越界访问导致未定义的行为,这很糟糕。


else 语句仅用于复制非白色space 字符,但你应该已经放弃该代码(如果它不是你的)并从头开始 or/and 先睹为快在:Encode/Decode URLs in C++.


至于错误的结果,你应该知道达到那个答案的那个点,这是意料之中的。

尝试就地修改很棘手。创建新字符串要容易得多:

std::string new_string;
for (int i = 0; i < str.length(); ++i) {
    if (str[i] == ' ')
        new_string += "%20";
    else
        new_string += str[i];
}
return new_string;

或者,如果你喜欢 range-for:

std::string new_string;
for (char ch : str) {
    if (ch == ' ')
        new_string += "%20";
    else
        new_string += ch;
}
return new_string;

这是错误的:

str[newLength] = '[=10=]';

std::string 对象根据其大小在内部维护其 NUL 终止符。你要

str.resize(newLength);

相反。

你可以把函数中的那个字符串参数改成引用,这样就不需要新的字符串了,在代码的其他部分,你可以用insert函数加上'2'和'0',就可以了只需要将 space 转换为 '&'.

void replaceSpaces(string &str) {
        size_t strLen = str.length();
        for (int i = 0; i < strLen; i++) {
            if (str[i] == ' ') {
                str[i] = '%';
                str.insert(str.begin() + i + 1, '2');
                str.insert(str.begin() + i + 2, '0');
                strLen += 2;
            }
        }
    }

这很简单;将代码中的 examplestring 替换为您的字符串,并按您的意愿使用:

#include <iostream> //debug output
#include <string>

using std::string;
using std::cout;
using std::endl;

//the string to convert
string examplestring = "this is the example string for spaces into %20";

int main()
{
    int countspaces = 0; //its faster to fill a known size
    for (auto &x : examplestring)if (x == ' ')countspaces++; //counts spaces

    string newstring; //declare new string
    newstring.resize(examplestring.size() + (countspaces*3)); //pre-set size to make it run faster

    int newstringiterator = 0; //keep track of new string location

    //if ' '(space), place %20 in newstring and add 3 to iteration
    //else just place the letter and iterate

    for (int i=0;i<examplestring.size();i++)
    {
        if (examplestring[i] == ' ') 
        { 
            newstring.insert(newstringiterator, "%20");
            newstringiterator += 3;
        }
        else newstring[newstringiterator++] = examplestring[i];
    }

  //final newstring is the original with %20 instead of spaces. 
  cout << newstring << endl;

  system("PAUSE"); //to read console output
  return 0; //return to zero
}

这将输出 newstring,这是带有“%20”而不是空格的旧字符串。