c++ - 将逗号添加到存储在数组中的一组字符串

标签 c++ arrays string

我需要根据存储在 byteSizeBuffer 中的 position 为存储在数组中的每个字符串添加一个逗号。

std::string::iterator it;
    int position = 0;
    int totalSize = 0;
    for (int i = 0; i < numOfMPs+1; i++)
    {
        for (int j = 0; j < numOfMPs; j++)
        {
            if(totalSize < subSize)
            {
                switch(byteSizeBuffer[j]) {
                    case 2:
                        position = totalSize+4; //4 because in the string each byte is 2 characters (2*2=4)
                        totalSize = position;
                        it = sub_[i].begin()+position, ','; //inserts comma at iterator+position
                        break;
                    case 4:
                        position = totalSize+8;
                        totalSize=position;
                        it = sub_[i].begin()+position, ',';
                        break;
                    default:
                        cout << "An error has occured while splitting the Data";
                        break;
                }
            }
        }
    }
  1. 位置是我要插入逗号的位置。
  2. totalSize为仓位总和,不能超过subSize
  3. subsize 始终为偶数且始终为 34 字节~68 个字符
  4. 逗号被添加到每个相同的位置 数组中的字符串。

字符串看起来像: FG454F3423T5245G4G5H6546456Y54645G4456G45G60101000000101010111000001

存储在 bytesizeBuffer[] 中的位置存储为 2 或 4,表示字节数。

所以如果存储的数字是 4,4,4,4,2,4,4,2,2,2,2 我需要它看起来像: FG454F34,23T5245G,4G5H6546,456Y5464,5G44,56G45G60,10100000,0101,0101,1100,0001 ..........行尾不应添加逗号。

我上面的代码似乎不起作用,我想知道我是否以正确的方式进行处理,或者是否有更有效的方法来执行上述操作。

只是一些让我走上正轨的技巧/指针才是我真正想要的。 谢谢

最佳答案

您可以使用std::string::insert
http://en.cppreference.com/w/cpp/string/basic_string/insert

此外,不要忘记在每次插入后您的字符串大小都会发生变化,因此所有后续元素的位置也会发生变化。

关于c++ - 将逗号添加到存储在数组中的一组字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21115523/

相关文章:

javascript - React 中 OTP 输入字段的第一个输入自动对焦

JQuery:如何在一条语句中以字符串形式获取选择器的所有 html 属性?

c++ - ifstream getline 问题

JavaScript - 正则表达式删除代码/特殊字符/数字等

c++ - addNode 和 addChild 的区别

java - 返回数组的所有负数元素

string - 为什么 NSError 的 localizedDescription 说可选 ("description")?

c++ - 我的函数操作 std::string 产生了意想不到的结果

c++ - C++ TR2 文件系统库的状态如何?

c++ - 使用自定义分配器引用字符串的 std::basic_string 特化作为 std::string 的常量对象而无需开销?