码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-06-02 14:08:34      阅读:258      评论:0      收藏:0      [点我收藏+]

标签:c   style   class   blog   code   java   

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

1.通过indexOf函数

bubuko.com,布布扣
/*
*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);
}
bubuko.com,布布扣

 

2.通过strtok_r函数

bubuko.com,布布扣
/**
*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);
}
bubuko.com,布布扣

[Arduino] 逗号分隔文本到数组的两种方法,布布扣,bubuko.com

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

标签:c   style   class   blog   code   java   

原文地址:http://www.cnblogs.com/jqmtony/p/3763060.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!