使用strtok解析一个字符串数组

时间:2013-11-30 20:27:57

标签: c arduino

如何更改此代码,以便将我输入的内容解析为COM窗口中的输入字段。

void setup()
{
   Serial.begin(9600);     // opens serial port, sets data rate to 9600 bps
   Serial.println("starting");

}

void loop()
{
  char stringToParse[] = "this,is,the,string,we'll,parse";
  const char *delim  = ",";   //a comma is the delimiter

  char *firstItem;
  char *secondItem;
  char *thirdItem;
  char *fourthItem;
  char *fifthItem;
  char *sixthItem;
  char *seventhItem;

  firstItem = strtok(stringToParse,delim);
  secondItem = strtok(NULL,delim);
  thirdItem = strtok(NULL,delim);
  fourthItem = strtok(NULL,delim);
  fifthItem = strtok(NULL,delim);
  sixthItem = strtok(NULL,delim);
  seventhItem =strtok(NULL,delim);

  Serial.print ("First item in string: ");
  Serial.println(firstItem);
  Serial.print ("Second item in string: ");
  Serial.println(secondItem);
  Serial.print ("Third item in string: ");
  Serial.println(thirdItem);
  Serial.print ("Fourth item in string: ");
  Serial.println(fourthItem);
  Serial.print ("Fifth item in string: ");
  Serial.println(fifthItem);
  Serial.print ("Sixth item in string: ");
  Serial.println(sixthItem);

  Serial.print ("seventh item in string: ");
  Serial.println(seventhItem);

  delay (5000); 
}

例如,我输入一,二,三,四 它输出 字符串中的第一项:一 字符串中的第二项:两项 字符串中的第三项:三项 字符串中的第四项:四个

2 个答案:

答案 0 :(得分:0)

这适用于任何输入字符串:

char * item = strtok (stringToParse, delim);
while (item != NULL)
{
  Serial.println(item);
  item = strtok (NULL, delim);
}

答案 1 :(得分:0)

要读取字符串,可以为其分配内存,然后从Serial:

添加字节
#define MAX_STR_CHARS 100
char stringToParse[MAX_STR_SIZE+1]="";
//...
void loop() {
    char b;
    int s;
    if (Serial.isAvailable()) {
        b=Serial.read();
        switch (b) {
        //Some possible string delimiters:
        case 0x0a: //LF
        case 0x0d: //CR
        case 0:    //NULL
            Serial.print("Received string is: ");
            Serial.println(stringToParse);
            //do you thing with string...
            *stringToParse=0; //reset string to next use
            break;
        default: //Add characters:
            s=strlen(stringToParse);
            if (s<MAX_STR_CHARS) { //Ensure is not writing after allocated buffer
                stringToParse[s]=b;
                stringToParse[s+1]=0;
            }
        }
    }
}