0

i have a string and i want to split it based on | so i can call that part if i need, please check the example below

String test= "first|Second|third";

so how can i use like

string1="first";

string2="second";

string3="third";

or word[0],word[1],word[2]

i dont know what to try coz im new in arduino

in php i wouold do like this: explode("|", test) so i hope my question is clear

wuqn yqow
  • 55
  • 6
  • Do you have [Arduino STL](https://www.arduinolibraries.info/libraries/arduino-stl) installed and/or does [this](https://stackoverflow.com/questions/14265581/parse-split-a-string-in-c-using-string-delimiter-standard-c) answer your question? – Ted Lyngmo Mar 05 '20 at 21:10
  • Does the `String` class have any methods to find characters in a string and return the position? Does the `String` class have a substring method? – Thomas Matthews Mar 05 '20 at 21:40
  • You could convert if to a char array using the method `toCharArray()` and then use `strtok` – at77 Mar 05 '20 at 22:30
  • 1
    How is this question related to Lua? – lhf Mar 06 '20 at 09:38

2 Answers2

0

I tested the following code on my Arduino and it works. You will need to modify it to fit your needs.

I would suggest not to use the Arduino String library because it uses dynamic memory and can cause programs to crash unpredictably because there is not enough memory or due to memory fragmentation. Fixed size buffers are definitely better on a microcontroller with just 2K of RAM.

void setup()
{
  Serial.begin(9600);
  int i;
  char delimiter[] = "|";
  char *p;
  char string[128];
  String test = "first|Second|third";
  String words[3];

  test.toCharArray(string, sizeof(string));
  i = 0;
  p = strtok(string, delimiter);
  while(p && i < 3)
  {
    words[i] = p;
    p = strtok(NULL, delimiter);
    ++i;
  }

  for(i = 0; i < 3; ++i)
  {
    Serial.println(words[i]);
  }
}

void loop() {
}
at77
  • 322
  • 2
  • 11
0

Arduino has very limited resources and C strings are much better in this environment. If you do not need to preserve the original one I usually amend that string.

char **split(char **argv, int *argc, char *string, const char delimiter, int allowempty)
{
    *argc = 0;
    do
    {
        if(*string && (*string != delimiter || allowempty))
        {
            argv[(*argc)++] = string;
        }
        while(*string && *string != delimiter) string++;
        if(*string) *string++ = 0;
        if(!allowempty) 
            while(*string && *string == delimiter) string++;
    }while(*string);
    return argv;
}

int main()
{
    char str[] = "first||Second|||third";
    char str1[] = "first||Second|||third";
    char *argv[8];
    int argc;

    split(argv, &argc, str, '|', 0);
    for(int i = 0; i < argc; i++) printf("argv[%d] = %s\n", i, argv[i]);
    printf("-----------------\n");
    split(argv, &argc, str1, '|', 1);
    for(int i = 0; i < argc; i++) printf("argv[%d] = %s\n", i, argv[i]);
}
0___________
  • 34,740
  • 4
  • 19
  • 48