1

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);
        }
}
guyd
  • 1,033
  • 2
  • 16
  • 51

1 Answers1

1
// concat version
void msgSplitter(const char* msg_in, int chop_size, char *prefix) {
  char tmp[50];
  int size = strlen(msg_in);
  for (int pos = 0, k = 0; pos < size; pos += chop_size) {
    int l = sprintf(tmp, "%s %d: ", prefix, k++);
    strncat(tmp + l, msg_in + pos, chop_size);
    Serial.println(tmp);
  }
}

// only value version
void msgSplitter(const char* msg_in, int chop_size, char *prefix) {
  char tmp[chop_size + 1];
  tmp[chop_size] = 0;
  int size = strlen(msg_in);
  for (int pos = 0; pos < size; pos += chop_size) {
    strncpy(tmp, msg_in + pos, chop_size);
    Serial.println(tmp);
  }
}
Juraj
  • 18,037
  • 4
  • 29
  • 49