简体   繁体   English

在C ++中将字符串拆分为4个字符

[英]Splitting a string by 4 chars in c++

i have a question regarding splitting a string. 我有一个关于拆分字符串的问题。 I am working on creating a binary to Hex converter, and want to split up my binary sequence that is represented as a string by 4 chars so that I can easily convert each set of 4 bits into a hexadecimal form: 我正在创建一个二进制到十六进制的转换器,并希望将我的二进制序列(由4个字符表示为一个字符串)拆分,以便我可以轻松地将每组4位转换为十六进制形式:

Example: 例:

00000111010110111100110100010101

would turn into: 会变成:

"0000", "0111", "0101", "1011", "1100", "1101", "0001", "0101"

Thank you for any assistance you can provide! 感谢您提供的任何帮助!

Using the std::string::substr function and a simple for loop you can just sub-divide the string into groups of 4 and push them into a std::vector<std::string> as shown below... 使用std::string::substr函数和简单的for循环,您可以将字符串细分为4组,然后将它们压入std::vector<std::string> ,如下所示...

#include <iostream>
#include <vector>
#include <string>

int main() {
    std::string nums = "00000111010110111100110100010101";
    std::vector<std::string> bins;

    for (std::size_t i = 0; i < nums.size(); i += 4)
        bins.push_back(nums.substr(i, 4));

    return 0;
}

Then bins becomes a std::vector filled with the sub-divided binary numbers. 然后bins变成一个std::vector里面充满了细分的二进制数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM