How to split a string using a specific delimiter in Arduino?

后端 未结 2 1758
轮回少年
轮回少年 2020-12-19 06:11

I have a String variable and I want to extract the three substrings separeted by ; to three string variables.

String application_command = \"{10,12; 4,5; 2}\         


        
相关标签:
2条回答
  • 2020-12-19 06:39

    The new SafeString Arduino library (available from the library manager) provides a number of tokenizing/substring methods without the heap fragmentation of the String class

    See
    https://www.forward.com.au/pfod/ArduinoProgramming/SafeString/index.html
    for a detailed tutorial

    In this case your can use

    #include "SafeString.h"
    
    void setup() {
      Serial.begin(9600);
    
      createSafeString(appCmd, 50);  // large enought for the largest cmd
      createSafeString(token1, 20);
      createSafeString(token2, 20);
      createSafeString(token3, 20);
      appCmd = "{10,12,13,9,1; 4,5; 2}";
      size_t nextIdx = 1; //step over leading {
      nextIdx = appCmd.stoken(token1, nextIdx, ";}");
      nextIdx++; //step over delimiter
      nextIdx = appCmd.stoken(token2, nextIdx, ";}");
      nextIdx++; //step over delimiter
      nextIdx = appCmd.stoken(token3, nextIdx, ";}");
      nextIdx++; //step over delimiter
      // can trim tokens if needed e.g. token1.trim()
      Serial.println(token1);
      Serial.println(token2); 
      Serial.println(token3);
    }
    
    void loop() {
    }
    

    Also look at pfodParser which parses these types of messages { } for use by pfodApp.

    0 讨论(0)
  • 2020-12-19 06:40

    I think you need a split-string-into-string-array function with a custom separator character.

    There are already several sources on the web and at stackoverflow (e.g. Split String into String array).

    // https://stackoverflow.com/questions/9072320/split-string-into-string-array
    String getValue(String data, char separator, int index)
    {
      int found = 0;
      int strIndex[] = {0, -1};
      int maxIndex = data.length()-1;
    
      for(int i=0; i<=maxIndex && found<=index; i++){
        if(data.charAt(i)==separator || i==maxIndex){
            found++;
            strIndex[0] = strIndex[1]+1;
            strIndex[1] = (i == maxIndex) ? i+1 : i;
        }
      }
    
      return found>index ? data.substring(strIndex[0], strIndex[1]) : "";
    }
    

    You can use this function as follows (with ";" as separator):

    String part01 = getValue(application_command,';',0);
    String part02 = getValue(application_command,';',1);
    String part03 = getValue(application_command,';',2);
    

    EDIT: correct single quotes and add semicolons in the example.

    0 讨论(0)
提交回复
热议问题