SparkFun Forums 

Where electronics enthusiasts find answers.

For the discussion of Arduino related topics.
By MRbling
#199040
Hello!

Say I have a String with data separatet by "," NumX = 00123,456,789,1011,1213,,14,15,1617.

How would I be able to isolate "1011" from this string into an int variable?

I'm not quite able to figure it out from other forums and it just don't feels like it should be that difficult!
By jremington
#199043
It is best to avoid Strings on Arduino, because they cause memory problems and eventual program crashes.

Instead, use character arrays (C-strings) and the reliable functions that go with them. For example:
Code: Select all
  char NumX[] = "00123,456,789,1011,1213,,14,15,1617";
The function strtok() can be used to search NumX for commas and isolate the individual C-strings containing the ASCII numbers.

The function atoi() will convert those into int variables. https://www.geeksforgeeks.org/strtok-st ... -examples/
By lyndon
#199044
This will return an array of substrings using the delimiters " ,/"
Code: Select all
// Separate string into tokens
inline void split(char* inVal, char outVal[NUM_WORDS][STRING_LEN])
{
    int i = 0;
    char *p = strtok(inVal, " ,/");
    strcpy(&outVal[i++][0], p);
    while (p)
    {
        p = strtok(NULL, " ,/");
	if (p)
	{
	    strcpy(&outVal[i++][0], p);
	}
    }
}
Offered as-is, no warranties, no support.