我需要根据存储在position
中的byteSizeBuffer
为存储在数组中的每个字符串添加一个逗号。
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;
}
}
}
}
字符串看起来像: 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 ..........不应该在行尾添加逗号。
我的上述代码似乎不起作用,我想知道我是否正确地采用了这种方法,或者是否有更有效的方法来完成上述工作。
让我走上正轨的一些提示/指示真的是我正在寻找的。 感谢
答案 0 :(得分:1)
您可以使用std::string::insert
http://en.cppreference.com/w/cpp/string/basic_string/insert
另外,请不要忘记每次插入后,您的字符串大小会发生变化,从而导致所有前进元素的位置发生变化。
答案 1 :(得分:0)
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++)
{
/* mp_subSize*2: each byte is 2 chars long so we have to get the full
* length of the string according to the characters
* +numOfMPs-1: adds the numOfMPs and then subtracts the final size from the buffer and -1 for the comma
* so that there is no comma added at the end of the string.
*/
if(totalSize < _subSize*2+numOfMPs-(byteSizeBuffer[count-1]*2)-1)
{
switch(byteSizeBuffer[j]) {
case 2:
position = totalSize+4; //4 because in the string each byte is 2 characters (2*2=4)
totalSize = position+1; //number of bytes +1 for the comma
break;
case 4:
position = totalSize+8;
totalSize=position+1;
break;
default:
cout << "An error has occured while splitting the Data";
break;
}
//this line adds the comma
it = sub_[i].insert(sub_[i].begin()+position, ',');
}
}
totalSize=0;
position=0;
}
更有效的方法是将其置于评论中所说的 @Roddy 之类的功能中。然而,这就是我提出的并且它有效。