Split string into parts

I have a String want to split it into 3 different strings

String s = “firstString, secondString, thirdString”

I want to split the string with the delimiter of “,”

The sting length varies, each part not a constant length.

So far I have, splits the string with delimiter.

Now I want string a= the first part so “firstString”
string b= the second part so “secondString”
string c= the third part so “thirdString”

#include <iostream>
#include <string>

std::string a;
std::string b;
std::string c;
std::string s = "firstString,secondString,thirdString";
std::string delim = ",";

int main()
{
    auto start = 0U;
    auto end = s.find(delim);
    while (end != std::string::npos)
    {
        std::cout << s.substr(start, end - start) << std::endl;
        start = end + delim.length();
        end = s.find(delim, start);
    }

    std::cout << s.substr(start, end);
    std::cout << a;
    std::cout << b;
    std::cout << c;
    
}

Post #9

Just note myString and String s are two very different strings to parse.
check the spacing, case etc. Be careful.

Sorry meat to be s - edited

Thank you I am a bit closer to my goal.

I loop through the function and send new data for the string. The string is actually hex so I first change it to char and that then makes up the string. Works fine.

String sent is "firstString,secondString,thirdString,fourthSting"

Now I split the string and I index it -- strs[i] -- output as below.

0: "firstString"
1: "secondString"
2: "thirdString"
3: "fourthSting" 

Now I send a update for the string "1String,2String,3String,4Sting", now the out put is

0: "firstString"
1: "secondString"
2: "thirdString"
3: "fourthSting"
4: "fourthSting"
5: "1String"
6: "2String"
7: "3String"
8: "4Sting"

So it kept the old strs[i] and add the new string to it.

How do I fix it so that the output is

1: "1String"
2: "2String"
3: "3String"
4: "4Sting"

My code

if (fPort == 100)

        {decoded = "";

        a = "";

        for (int i = 0; i < dataLength; i++){

            a = static_cast<char>(data[i]);

            decoded += a;

        };

        }

    // Split string

    while (decoded.length() > 0)

  {

    int index = decoded.indexOf(',');

    if (index == -1) // No space found

    {

      strs[StringCount++] = decoded;

      break;

    }

    else

    {

      strs[StringCount++] = decoded.substring(0, index);

      decoded = decoded.substring(index+1);

    }

  }

    for (int i = 0; i < StringCount; i++)

  {

    Serial.print(i);

    Serial.print(": \"");

    Serial.print(strs[i]);

    Serial.println("\"");

  };

    line1 = strs[0];

    line2 = strs[1];

    line3 = strs[2];

    line4 = strs[3];

    printOled();```

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