首页 > 代码库 > [Arduino] 逗号分隔文本到数组的两种方法

[Arduino] 逗号分隔文本到数组的两种方法

以下是今日练习通过逗号来分割字符数组/字符串的2个例子和方法“

1.通过indexOf函数

/*
*Splitsplit sketch
*split a comma-separated string
*/

String message = "Peter,Paul,Mary";
int commaPosition;

void setup(){
  Serial.begin(9600);
}

void loop(){
   Serial.println(message);
   do{
      commaPosition = message.indexOf(,);
      if(commaPosition != -1)
      {
         Serial.println(message.substring(0,commaPosition));
         message=message.substring(commaPosition+1,message.length()); 
       //  Serial.println(message);
      }
      else{
        if(message.length()>0){
           Serial.println(message);
        }
      }
   }
   while(commaPosition>=0);
  // if(message=="Mary")
  // while(1);
   delay(5000);
}

 

2.通过strtok_r函数

/**
*SplitSplit sketch
*split a commaPosition string
**/

const int MAX_STRING_LEN = 20;
char stringList[] = "Peter,Paul,Mary";
char stringBuffer[MAX_STRING_LEN+1];

void setup(){
  Serial.begin(9600);
}

void loop(){
  char *str;
  char *p;
  strncpy(stringBuffer,stringList,MAX_STRING_LEN);
  Serial.println(stringBuffer);
  for(str=strtok_r(stringBuffer,",",&p); //split using comma
     str;   //loop while str is not null
     str = strtok_r(NULL,",",&p) //get subsequent tokens
     ){
     Serial.println(str);
     if(strcmp(str,"Paul")==0)
        Serial.println("found Paul"); 
     }

     delay(5000);
}

/* strtok_r()
str=strtok_r(stringBuffer,",",&p) //把stringBuffer按逗号拆分,
//拆分后数值首地址付给指针p,数值赋值给指针str
*/

提取逗号中数值:

/*
*SplitSplit sketch
*Split a comma-separted string
*/
const int MAX_STRING_LEN =20;
char stringList[] = "H,10,1050,15000,/r/n";
char stringBuffer[MAX_STRING_LEN + 1];
void setup(){
  Serial.begin(9600);
}

void loop(){
  char *str;
  char *p;
  char index = 0;
  strncpy(stringBuffer,stringList,MAX_STRING_LEN);
  Serial.println(stringBuffer);
  for(str=strtok_r(stringBuffer,",",&p);
     str;
     str=strtok_r(NULL,",",&p)
     )
   {
     index ++;
     Serial.println(str);
     if(strcmp(str,"H")==0)
        Serial.println("found HEADER");
       
        Serial.println();
       
        if(strlen(str)==2){  //if not 2 digital,it is easy to error
          Serial.print("value1 = " );
          Serial.println(str);}
       
         if(index==3){
          Serial.print("value2 = " );
          Serial.println(str);} 
         
         if(index==4){
          Serial.print("value3 = " );
          Serial.println(str);}    
         
     }
   
    delay(50000);
}