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);
        }
}
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);
  }
}
  • Can you answer my 2nd cquestion ? – Guy . D Nov 3 '18 at 10:42
  • the second version of the function in my answer is it. replace println with the publishing function – Juraj Nov 3 '18 at 10:43
  • You Rock Juraj! – Guy . D Nov 3 '18 at 10:45
  • U2 :) ( cough cough ) – Guy . D Nov 3 '18 at 18:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.