I have a variable string, that I need to slice into smaller strings, the main string should be treated as a bidimensional array with a certain width and height MxM, and the smaller strings should be cut in blocks of NxN size. So for example, if I have the following string, char source[17] = "ABCDEFGHIJKLMNS0"
and his bidimensional size is 4x4, and the size of the smaller blocks are 2x2, the smaller blocks should be ABEF
, CDGH
, IJMN
, KLSO
.
In other words, the string should be seeing as
ABCD
EFGH
IJKL
MNSO
and NxN should be cut from it, like:
AB
EF
Always with the constraint that these blocks should be linear arrays as the main string.
I have tried with 3 nested for, with the following code, but I didn't know how to calc the index of the main array in order to cut the blocks that way
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main()
{
char pixelsSource[17] = "ABCDEFGHIJKLMNS0";
char pixelsTarget[4][5];
int Y = 0;
int X = 0;
for (int block = 0; block < 4; block++)
{
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
pixelsTarget[block][(i * 2) + j] = pixelsSource[(i * 2) + j];
printf("[%d][%d] = [%d]
", block, (i * 2) + j, (i * 2));
}
}
}
for (int block = 0; block < 4; block++)
{
printf("%s
", pixelsTarget[block]);
}
}
question from:
https://stackoverflow.com/questions/65878085/slice-variable-length-char-array 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…