Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Splitting strings by a delimiter for Arduino
//
// This is tested and works!
//
String input = "123,456";
int firstVal, secondVal;
for (int i = 0; i < input.length(); i++) {
if (input.substring(i, i+1) == ",") {
firstVal = input.substring(0, i).toInt();
secondVal = input.substring(i+1).toInt();
break;
}
}
//
// I tested a similar version in JS and it worked
// No guarantees!!
//
// Define number of pieces
const int numberOfPieces = 4;
String pieces[numberOfPieces];
// This will be the buffered string from Serial.read()
// up until you hit a \n
// Should look something like "123,456,789,0"
String input = "";
// Keep track of current position in array
int counter = 0;
// Keep track of the last comma so we know where to start the substring
int lastIndex = 0;
void setup(){
Serial.begin(9600);
}
void loop() {
// Check for data coming in from serial
if (Serial.available() > 0) {
// Read the first byte and store it as a char
char ch = Serial.read();
// Do all the processing here since this is the end of a line
if (ch == '\n') {
for (int i = 0; i < input.length(); i++) {
// Loop through each character and check if it's a comma
if (input.substring(i, i+1) == ",") {
// Grab the piece from the last index up to the current position and store it
pieces[counter] = input.substring(lastIndex, i);
// Update the last position and add 1, so it starts from the next character
lastIndex = i + 1;
// Increase the position in the array that we store into
counter++;
}
// If we're at the end of the string (no more commas to stop us)
if (i == input.length() - 1) {
// Grab the last part of the string from the lastIndex to the end
pieces[counter] = input.substring(lastIndex, i);
}
}
// Clear out string and counters to get ready for the next incoming string
input = "";
counter = 0;
lastIndex = 0;
}
else {
//if we havent reached a newline character yet, add the current character to the string
input += ch;
}
}
// Data is now available in pieces array
// pieces[0] is first item
// pieces[1] is second item, and so on
// You can call toInt() on the data to convert it to an int
// ex. int value = pieces[0].toInt();
}
@adielfernandez

This comment has been minimized.

Copy link

commented Apr 5, 2014

Partially works but it got me on the right track to get it working really well, so thanks! I made a few edits (some below) and packaged it together with other code and sent it out to the world.

-The last if statement needs to be in the for loop
-lastIndex and counter need to be reset for the next string
-Arduino doesnt allow declarations of arrays with variables for the length (i.e. String pieces[numberOfPieces] is now String pieces[4])
-I also changed the pieces String array to a long array and called toInt() on the substring.

Thanks again!

@mattfelsen

This comment has been minimized.

Copy link
Owner Author

commented Apr 5, 2014

Thanks for putting together a working example for everyone! Good catches all around

  • Tthe last if statement worked in JS but now I see that i goes out of scope for C
  • Why move away from a String array? It'd be useful to be able to send strings like "1,48,bob" you know? Keep everything as Strings and then call .toInt() and things you need?
@adielfernandez

This comment has been minimized.

Copy link

commented Apr 5, 2014

Thanks! "1,48,bob" Yessss, thats totally true. Then you could send "coded" variables so the arduino knows to change a specific one instead of constantly streaming variables that might not need changing all the time. Good idea.

That if statement works in JS?? JS is weird...

@mattfelsen

This comment has been minimized.

Copy link
Owner Author

commented Apr 5, 2014

Yes, JS doesn't have block-level scope, just global & function. Once the for loop exits, i retains its value until the end of the loop() function and then is destroyed. Maybe I should put up a site for doesjavascripthaveblocklevelscope.com…

Also, sure, you can codify useful, semantic string values into int values, but you could also not.

@balajyothi

This comment has been minimized.

Copy link

commented Sep 23, 2017

Hi JS, the above code is well working for number to split like 123,456.

But I have 10 bytes to be splitted,can you please suggest how it can be done with arduino.

@farshid616

This comment has been minimized.

Copy link

commented Jun 2, 2018

Thanks For this code, it's handy but i found a bug and i solved it.

  • Last pieces of splitted string missed last character. pieces[counter] = input.substring(lastIndex, i); in line 65 i must changed by input.length()
@mickeypop

This comment has been minimized.

Copy link

commented Sep 3, 2018

This has always worked for me

// String  var = getValue( StringVar, ',', 2); // if  a,4,D,r  would return D        
String getValue(String data, char separator, int index)
{
    int found = 0;
    int strIndex[] = { 0, -1 };
    int maxIndex = data.length();

    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]) : "";
}  // END
@PululuK

This comment has been minimized.

Copy link

commented Feb 26, 2019

@mickeypop work for me ! Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.