Split String into String array

前端 未结 6 1839
小蘑菇
小蘑菇 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:13

    This is an old question, but i have created some piece of code that may help:

     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]) : "";
    }
    

    This function returns a single string separated by a predefined character at a given index. For example:

    String split = "hi this is a split test";
    String word3 = getValue(split, ' ', 2);
    Serial.println(word3);
    

    Should print 'is'. You also can try with index 0 returning 'hi' or safely trying index 5 returning 'test'.

    Hope this help!

提交回复
热议问题