I am looking for a method to split my string on my Arduino. Which library or something else can I use?
2 Answers
Here is a solution that replaces a delimiter with end of string character and then uses an array you pass into the function to set each index to where the separated string starts. Effectively giving you a string for each part of the string input and returning the number of splits found.
It does not do any checks to the number of elements in the array. So you might want to add that if you don't know what the input data is.
I had this issue when parsing MQTT topics and didn't want to add any data structures or copy memory because of performance and lack of space in the microcontroller.
uint8_t str_split_in_place(char* str, char delim, char** string_pointers) {
string_pointers[0] = str;
Serial.println(string_pointers[0]);
uint8_t assigned_pointers = 1;
while(*str != '\0') {
if (*str == delim) {
string_pointers[assigned_pointers++] = str+1;
*str = '\0'; // insert end of string where the delimiter is
}
str++;
}
return assigned_pointers;
}
Example usage in Arudino:
void setup() {
Serial.begin(115200);
char input[] = "here/is/a/topic";
char* topic_parts[5]; // note the 5. There can only be five parts unless you increase it.
uint8_t parts_count = str_split_in_place(input, '/', topic_parts);
for(int i = 0; i < parts_count; i++) {
char* topic_part = topic_parts[i];
Serial.print("topic_part ");
Serial.print(i);
Serial.print(": ");
Serial.println(topic_part);
}
}
strtok()from the C standard library?char*or an ArduinoString?