我有一个程序创建一个动态字符串数据输入(不允许使用c ++字符串),看起来像这样(而不是日期可以基本上是任何其他数据,并且没有给出数据块的数量) :
2004-01-18 | 2005-01-18 |
我需要对字符串进行分割,将其拆分为可用于打印的单数据块的二维字符数组。我的代码看起来像这样:
char** CRegister::Split(char *st, int& parts, int& maxChars) const{
parts = 0;
maxChars = 0;
int maxtmp = 0;
int j = 0;
/* Calculating the number of data blocks in the string */
while(st[j]){
if(st[j] == '|'){
parts++;
}
j++;
}
j = 0;
/* Calculating the longest data block length for array initialization */
while(st[j]){
if(st[j] != '|'){
maxtmp++;
}
else{
if(maxtmp > maxChars){
maxChars = maxtmp;
}
maxtmp = 0;
}
j++;
}
j = 0;
cout << "!!!!!-----!!!!!-" << st << "-!!!!!!!-----!!!!!" << endl;
/* Initialization of the dara array */
char **array = new char*[parts];
for(int i = 0; i < parts; i++){
array[i] = new char[maxChars];
}
/* Filling the array with data blocks */
int p = 0;
for(int i = 0; i < parts; i++){
while(st[j] != '|'){
array[i][p] = st[j];
j++;
p++;
}
if(st[j] == '|'){
j++;
}
p = 0;
}
return array;
}
从大多数情况来看,它只是按照我需要的方式工作,但问题是它有时会出现不可预测的行为,破坏了整个程序 - 数据块并没有在它们应该的地方结束而是一堆添加其他字符(通常是以前使用过的单词的一部分)。结果看起来像这样(“!!!!! ----- !!!!! - ”之间的界线是预处理数组)
!!!!!-----!!!!!-2003-01-18|-!!!!!!!-----!!!!!
!!!!!-----!!!!!-Whiston's street|-!!!!!!!-----!!!!!
!!!!!-----!!!!!-Miami|-!!!!!!!-----!!!!!
2003-01-18 Whiston's street Miami
!!!!!-----!!!!!-2004-01-18|2005-01-18|-!!!!!!!-----!!!!!
!!!!!-----!!!!!-Whiston's street|Someone's streetz|-!!!!!!!-----!!!!!
!!!!!-----!!!!!-Miami|Siberia|-!!!!!!!-----!!!!!
2004-01-18 Whiston's street Miami
2005-01-18street Someone's streetz Siberia
!!!!!-----!!!!!-2004-01-18|-!!!!!!!-----!!!!!
!!!!!-----!!!!!-Whiston's street|-!!!!!!!-----!!!!!
!!!!!-----!!!!!-Miami|-!!!!!!!-----!!!!!
2004-01-18 Whiston's street Miami
!!!!!-----!!!!!-2004-01-18|-!!!!!!!-----!!!!!
!!!!!-----!!!!!-Whiston's street|-!!!!!!!-----!!!!!
!!!!!-----!!!!!-Miami|-!!!!!!!-----!!!!!
2004-01-18streetz Whiston's street Miami
对于三个不同的数据集,连续三次调用该函数,然后连续打印。
答案 0 :(得分:1)
如果您不能使用标准字符串类,请编写自己的简化版本,并使用它。
然后与std::vector
大致相同 - 使用它,或者编写自己的简化版本。
当你完成这两项工作时,编写这个函数来将输入解析成my_vector<my_string>
应该完全无关紧要。