Split String into String array

前端 未结 6 1835
小蘑菇
小蘑菇 2020-12-31 08:14

I have been playing around with programming for arduino but today i\'ve come across a problem that i can\'t solve with my very limited C knowledge. Here\'s how it goes. I\'m

6条回答
  •  长发绾君心
    2020-12-31 09:15

    I believe this is the most straight forward and quickest way:

    String strings[10]; // Max amount of strings anticipated
    
    void setup() {
      Serial.begin(9600);
      
      int count = split("L,-1,0,1023,0", ',');
      for (int j = 0; j < count; ++j)
      {
        if (strings[j].length() > 0)
          Serial.println(strings[j]);
      }
    }
    
    void loop() {
      delay(1000);
    }
    
    // string: string to parse
    // c: delimiter
    // returns number of items parsed
    int split(String string, char c)
    {
      String data = "";
      int bufferIndex = 0;
    
      for (int i = 0; i < string.length(); ++i)
      {
        char c = string[i];
        
        if (c != ',')
        {
          data += c;
        }
        else
        {
          data += '\0';
          strings[bufferIndex++] = data;
          data = "";
        }
      }
    
      return bufferIndex;
    }
    

提交回复
热议问题