I have a string to be splitted into define chunks.
For example new_str="abcdefghjklmnopqrstuvwxyz, and my goal is to split it to chunks of split_size=5, so the result should be :abcde,fghij and so o.
new_str gets every time a different string.
split_size can be any size.
I have 2 questions:
1) Attached code does the job, but looks a BIT not elegant for a newbie like me. is there another way doing it ?
2)In code attached, output is Serial.println(tmp) and should be replaced with an output function to post each chunk to as a MQTT message. Ive rather that each chunk would be stored into a global array, to be sent later on in code out side msgSplitter.
So I wrote the following code:
int split_size=5;
char new_str[]="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
void setup() {
Serial.begin(9600);
Serial.print("String length: ");
Serial.println(strlen(new_str));
Serial.print("Split Size: ");
Serial.println(strlen(split_size));
msgSplitter(new_str, split_size, "Split #");
}
void msgSplitter( const char* msg_in, int chop_size, char *prefix){
num=ceil((float)strlen(msg_in)/chop_size);
char tmp[50];
int pre_len;
if (num > 1) {
for (int k=0; k<num; k++) {
pre_len=0;
sprintf(tmp,"%s %d: ",prefix,k);
pre_len = strlen(tmp);
for (int i=0; i<chop_size; i++) {
tmp[i+pre_len]=(char)msg_in[i+k*chop_size];
tmp[i+1+pre_len]='\0';
}
Serial.println(tmp);
}
}
else {
Serial.println(msg_in);
}
}