Arduino: String to Array Conversion based on delimiter

arduino_logo-wallpaper-1920x1200

This is a simple sketch on how to convert any String to Array in Arduino based on any token or delimiter. Whenever you are working on any project which involves data transfer between Arduino and Other devices/micro-controllers using serial or Wi-Fi or Ethernet you might need to transfer chunks of data and usually the data are not mapped unless you are using JSON or XML. Use of JSON and XML works fine, but proper parser needs to be added to the micro-controller to parse the encoded data.  So if required the data containing multiple info or values can be transferred between devices by separating them with specific delimiter like some special characters (#,$,%, etc. ) forming a single string. However, make sure the delimiter used to separate values is not present in the content. Otherwise, it may lead to parsing issue.

 

 

For example let’s take a string of data separated by ‘,‘ (You can use any other character instead of, but make sure it doesn’t appear inside the data values.)

String abc="525,45,44,545,abc";

The following code breaks the string and put the separate values into an array.

Code
String abc="525,45,44,545,abc";

void getTokens(String *dataTokens,String abc, char deliminetor);
String dataTokens[10];

void setup() {
  Serial.begin(9600);
  
  getTokens(dataTokens,abc,',');
  for(int i=0;i<5;i++)
    Serial.println(dataTokens[i]);
    delay(2000);
}

void loop() {
//loop code goes here
}

void getTokens(String *dataTokens,String abc, char deliminetor){
  int i=0;
  while(abc.indexOf(deliminetor)!=-1){
    dataTokens[i]=abc.substring(0,abc.indexOf(deliminetor));
    abc=abc.substring(abc.indexOf(deliminetor)+1,abc.length());
    i++;
  }
  dataTokens[i]=abc;
  return;
}

Bikash Panda
Catch Me On

Bikash Panda

Blogger / Embedded System Developer at WeArGenius
A techie, tinkerer and tech lover, who loves to blog and feels everyone can learn tech provided they have the right attitude towards learning and passion. By profession, I am an IOT developer working in Smart Home/ Smart Grid domain.
Bikash Panda
Catch Me On

Related posts