Replacing all spaces in a string with '%20' (C++)
<p>Having some trouble understanding parts of the code; the output I am getting is also wrong. The problem is to replace all spaces in a string with '%20'. The full code is shown below; it compiles but doesn't run exactly as it should. </p>

<pre><code>#include &lt;iostream&gt;
#include &lt;string&gt;
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 &lt;= 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 &gt;= 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 &lt;&lt; str &lt;&lt;endl;

}

int main() {

    string str = "hello jellybean hello";
    replaceSpaces(str);

    return 0;

}
</code></pre>

<hr>

<p>I am probably missing something obvious, but when allocating for the new string length in this line: </p>

<p><code>int newLength = strLen + count * 2;</code></p>

<p>Here we are multiplying the number of spaces by 2, but if we are trying to replace all spaces with '%20', why not multiply it by 3? </p>

<hr>

<p><code>str[newLength] = '\0';</code></p>

<p>Does this line indicate that the position past the last character in the string is assigned a null space? </p>

<hr>

<p>Am also confused about the <code>else</code> statement. </p>

<pre><code> else {
        str[newLength - 1] = str[i];
        newLength = newLength -1;
    }
</code></pre>

<p>Not sure if I completely understand the circumstance when this would be executed. </p>

<hr>

<p>When the functions are compiled and run, if </p>

<p><code>string str = "hello jellybean hello";</code></p>

<p>the expected output would be <strong>hello%20jellybean%20hello</strong>, except the output I am getting is <strong>hello%20jellybean%20h</strong>. </p>

<p>In terms of time complexity, since there are two independent <code>for</code> loops, would the time complexity be <em>O(n)</em>? </p>

<p>I know I'm asking a lot of different questions, many thanks in advance for any answers! </p>