I am trying to write a function that takes just two parameters (A string and a delimiter)
The function splits the string at the delimiter(s) and returns an array with the substrings as the values.
The string can contain any number of delimiters.
I have tried to do this in so many ways but keep failing. the first attempt i tried converting the String Object into an std::string type then used old school C++ tokens (using strtok_r) to get the values witch worked with the testing code (example below)
String msg = "10,20,30";
char buf[msg.length()+1];
msg.toCharArray(buf, sizeof(buf));
char *token;
char *pter = buf;
while ((token = strtok_r(pter, ",", &pter)))
{
Serial.println(token);
int numb =atoi(token) + 5;
Serial.println(numb);
//push token to the vector
}
//return vector
However as soon as I wrapped it in to a function (using an std::vectorstd::string as a return value) all i got was random characters in the serial console. witch i came to believe was because outside the function's scope the pointers become invalid.
So then I tried to create tokens using std::string::substr instead of strtok to get rid of the pointers (I don't fully understand pointers yet) however this time the serial did not even want to read the token value. after that I gave up on using the std liabery and moved back to just using String Objects.
So I tried constructing a new function using string.substring() to split the string.
void splitStringToArray(String msg, char delim)
{
int i;
Serial.println("length of string:" + msg.length());
int splits = 0;
while (i <= msg.length())
{
if(msg.charAt(i) == delim)
{
splits++;
}
i++;
}
String subStrings[splits];
int delimIndex[splits];
delimIndex[0]=0;
delimIndex[1] = msg.indexOf(delim);
i = 2;
while (i<splits)
{
delimIndex[i] = msg.indexOf(delim, delimIndex[i-1] + 1);
i++;
}
subStrings[0] = msg.substring(0, delimIndex[1]);
i=1;
while (i<strlen(subStrings))
{
subStrings[i] = msg.substring(delimIndex[i] + 1, delimIndex[i+1]);
i++;
}
//Test
i = 0;
while (i<=strlen(subStrings))
{
Serial.println(subStrings[i]);
i++;
}
}
I do realize that this is a void function but I was trying to get the test to work before i turn it in to a string object array function.
However now i'm getting errors that I literally cant even comprehend what they are saying at all.
cannot convert 'String*' to 'const char*' for argument '1' to 'size_t strlen(const char*)'
and well im starting to feel like it would be easier to work out how to add gravity to the standard model of quantum physics then work out how to split a string object into substrings that are stored in an array or vector.
So I was wondering if any one could help me formulate a function to achieve my goal? Thankyou =)