0

I am looking for a method to split my string on my Arduino. Which library or something else can I use?

4
  • Maybe strtok() from the C standard library? Commented Feb 19, 2013 at 19:50
  • 1
    You can use String.subString to do this Commented Feb 19, 2013 at 19:55
  • C or C++? It works totally different. Commented Feb 19, 2013 at 20:00
  • Is the string a char* or an Arduino String? Commented Feb 20, 2013 at 13:28

2 Answers 2

1

Does the strtok function defined in string.h not suit your purpose?

Sign up to request clarification or add additional context in comments.

Comments

0

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);
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.