Replace spaces with %20

Categories:

Problem

Replace all space characters in a string with %20 (percent-encoding).

Solution

encode_spaces.cpp
 1#include <algorithm>
 2#include <string>
 3
 4void url_encode(std::string& s) {
 5    const auto size = s.size();
 6
 7    const auto spaces = std::count_if(s.begin(), s.end(), [](const auto& c) { return c == ' '; });
 8    /* or using for loop:
 9    size_t spaces{};
10    for (size_t i = 0; i < size; ++i)
11        if (s[i] == ' ')
12            ++spaces;
13    //*/
14
15    const auto new_size = size + 2 * spaces;
16    s.resize(new_size);
17    for (int i = size - 1, j = new_size - 1; ~i; --i, --j) {  // `~i` is the same as `i >= 0`
18        if (s[i] == ' ') {
19            s[j--] = '0';
20            s[j--] = '2';
21            s[j] = '%';
22        } else s[j] = s[i];
23    }
24}