C++拆分字符串每X个字符 [英] C++ Split String Every X Characters

查看:40
本文介绍了C++拆分字符串每X个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个函数,该函数接受一个字符串,并拆分每 X 个字符:

I am trying to write a function that takes a string, and splits every X number of characters:

std::vector<std::string> DIFSplitStringByNumber(std::string s, int l)
{
    const char *c = s.c_str();  
    char buffer[l];
    std::vector<std::string> entries;
    entries.reserve(int(s.length() / l) + 1);

    int d = 0;   
    for(int i = 0; i < s.length() - 1;)
    {
        if(d != l)
        {
            buffer[d] = c[i];
            d++;
            i++;
        }
        else
        {
            entries.push_back(std::string(buffer, l));

            //Clear array
            memset(buffer, 0, l);
            d = 0;
        }       
    }

    return entries;
}

例如,如果我调用 DIFSplitStringByNumber("hello!", 2),我应该得到一个包含:

For example, If I called DIFSplitStringByNumber("hello!", 2), I should get a vector containing:

[0] he
[1] ll
[2] o!

然而,它似乎只得到前两个结果(向量大小为 2),当我执行类似 DIFSplitStringByNumber("hello", 2) 之类的操作时,它崩溃了,大概是因为它的试图访问不存在的数组索引(它需要 6 个字符,但只有 5 个).有没有更简单的方法来做到这一点?

However, it only seems to get the first two results (the vector size is 2), and when I do something like DIFSplitStringByNumber("hello", 2), it crashes, presumably because its trying to access an array index that doesn't exist (it expects 6 characters, but there are only 5). Is there a simpler way to do this?

推荐答案

这会将字符串拆分为向量.如果分割数不是偶数,则将额外的字符添加到末尾.

This will split a string into a vector. If there aren't an even number of splits, it will add the extra characters to the end.

std::vector<std::string> Split(const std::string& str, int splitLength)
{
   int NumSubstrings = str.length() / splitLength;
   std::vector<std::string> ret;

   for (auto i = 0; i < NumSubstrings; i++)
   {
        ret.push_back(str.substr(i * splitLength, splitLength));
   }

   // If there are leftover characters, create a shorter item at the end.
   if (str.length() % splitLength != 0)
   {
        ret.push_back(str.substr(splitLength * NumSubstrings));
   }


   return ret;
}

这篇关于C++拆分字符串每X个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆