[英]Convert 1D array with delimeters into 2D Array
我一直试图为此找到答案,但似乎无法理解如何实现:
我有以下数据:
0INDEX,DATE,PACKET
0,22:3:2021 4:31:51,B987620.00
0,22:3:2021 4:33:39,B987620.00
1,22:3:2021 4:33:46,B987620.00
这存储在一个一维数组中。 有一个“,”分隔符,每行的结尾用“/n”表示,并在上面的示例中显示为回车。
到目前为止一切都很好。
我写了以下 function:
char historyTableDataArray[100][5]; // I want this to contain the data above in a 2D array
char VALUE[512] = {'\0'}; // This is the 1D array that I want to process
for (int i = 0; i < 512; i++)
{
if (VALUE[i] == ','){
col++;
if(col==3){
col = 0;
}
}
else if (VALUE[i] == '\n'){
row++;
}
else{
// CAPTURE CHARACTERS HERE
historyTableDataArray[row][col] = VALUE[i];
}
}
我希望将字符附加到 historyTableDataArray 中的相应行/列,但我找不到这样做的方法。 上面的代码覆盖当前值。 我仅限于从一维数组开始的数据。 提前致谢!
目标数据应如下所示:
索引日期包
0 22:3:2021 4:31:51 B987620.00
0 22:3:2021 4:33:39 B987620.00
1 22:3:2021 4:33:46 B987620.00
你可以这样做:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define BUFF_SIZE 256
#define ROW_NB 100
#define COL_NB 5
int main(void) {
int col = 0;
int row = 0;
char historyTableDataArray[ROW_NB][COL_NB][BUFF_SIZE] = {0}; // I want this to contain the data above in a 2D array
char *s= "0,22:3:2021 4:31:51,B987620.00\n0,22:3:2021 4:33:39,B987620.00\n1,22:3:2021 4:33:46,B987620.00";
int i;
while (*s)
{
// Serial.println(VALUE[i]);
if (*s == ','){
col++;
i = 0;
// Serial.println("comma found");
}
else if (*s == '\n'){
historyTableDataArray[row][col][i] = '\0';
row++;
col = 0;
i = 0;
// Serial.println("CR found");
}
else {
// CAPTURE CHARACTERS HERE
historyTableDataArray[row][col][i++] = *s;
}
s++;
}
historyTableDataArray[row++][col++][i] = '\0';
for (i = 0; i< row; i++) {
for (int j = 0; j<col; j++) {
printf("%s\n", historyTableDataArray[i][j]);
}
}
我假设您已经将数据保存在 char *s 中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.