Arduino split data into 5 strings

So basically I want to make a void function that splits the parameter value into 5 global variables. So if I put "05:13:2021:11:06", the numbers should be divided and saved separately in global Strings called hour, minute, year, month, and day.

void loop() {
     splitData("05:13:2021:11:06");
     Serial.println(hour + ":" + minute + ", " + year + "/" + month + "/" + day);
}

void splitData(String string) {
     . . .
}

this should print out 05:13, 2021/11/06

can anyone give me some examples?

consider following just posted in another thread
add a parallel array of ints using atoi() of the tokens

char s [80];

#define MaxTok  10
char *toks [MaxTok];

// -----------------------------------------------------------------------------
int
tokenize (
    char       *s,
    const char *sep )
{
    unsigned n;
    toks [0] = strtok (s, sep);
    for (n = 1; (toks [n] = strtok (NULL, sep)); n++)
        ;

    return n;
}

// -----------------------------------------------------------------------------
void dispToks (
    char * toks [])
{
    for (unsigned n = 0; toks [n]; n++)
        Serial.println (toks [n]);
}

// -----------------------------------------------------------------------------
void loop ()
{
    if (Serial.available ())  {
        int n = Serial. readBytesUntil ('\n', s, sizeof(s));
        s [n] = 0;      // terminate string

        tokenize (s, ",");
        dispToks (toks);
    }
}

// -----------------------------------------------------------------------------
void setup ()
{
    Serial.begin (9600);
}
String hour, minute, year, month, day;

void splitData(String string)
{
  hour = string.substring(0, 2);
  minute = string.substring(3, 5);
  year = string.substring(6, 10);
  month = string.substring(11, 13);
  day = string.substring(14);
}

void setup()
{
  Serial.begin(115200);
  delay(200);
  
  splitData("05:13:2021:11:06");
  
  Serial.println(hour + ":" + minute + ", " + year + "/" + month + "/" + day);
}

void loop() {}

Simple is the best. Why did I forget about that? That's actually perfect because the length will always stay constant. Thanks

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.