Add whitespace to string at specific places

Viewed 486

I have a string "00000000000000000000010011010010". I want to add a whitespace after every eighth char to make it represent a 32 bit integer. For example: "00000000 00000000 00000100 11010010". What would be the simplest way to do this?

2 Answers

With the range-v3 library, the code is quite simple to understand:

using namespace ranges;
auto res = s | views::chunk(8) | views::join(' ') | to<std::string>;

Here's a demo.

Construct a new whitespace-delimited string

As insertions are a bit expensive, you may want to simply construct a new string and fill it from the original, adding spaces as appropriate after every substring of eight characters (save for the final substring).

#include <cstddef>
#include <iostream>
#include <string>

std::string chunked(const std::string& s,
                    const std::size_t chunk_size = 8U,
                    const char delimiter = ' ') {
    std::string result;
    const auto s_size = s.size();
    result.reserve(s_size + (s_size / chunk_size));

    for (std::size_t i = 0U; i < s_size; i += chunk_size) {
        result += s.substr(i, chunk_size);
        if (i + chunk_size < s_size) { 
            result += delimiter; 
        }
    }

    return result;
}

int main() {
    std::cout << chunked({"00000000000000000000010011010010"}); 
      // 00000000 00000000 00000100 11010010

    return 0;
}

Print the existing string as whitespace-delimited chunks

Alternatively, your use case may be to simply print the string as whitespace-separated 8-character chunks:

#include <cstddef>
#include <iostream>
#include <string>

void printAsChunks(const std::string& s, 
                   const std::size_t chunk_size = 8U) {
    for (std::size_t i = 0U; i < s.size(); i += chunk_size) {
        std::cout << s.substr(i, chunk_size) 
            << ((i + chunk_size < s.size()) ? " " : "");
    }
}

int main() {
    printAsChunks("00000000000000000000010011010010");
        // 00000000 00000000 00000100 11010010
    return 0;
}
Related