1

I have a string in C that i want to split in str_tok String is = 04_1,03_0,05_1 It works fine if split once.

        char* token = strtok(argv[2], ",");
        

        while (token != NULL) {
            printf("%s\n", token);
            token = strtok(NULL, ","); }

It will get 04_1 03_0 05_1 I want to split it again with the _ underscore as the delimiter

SOLUTION FOUND

char* token = strtok(argv[2], "_,");
token = strtok(NULL, "_,"); 
Dennis
  • 67
  • 7
  • 3
    If you set the delimiter to `"_,"`, the output will be `04 1 03 0 05 1`. Is that what you want? – user3386109 Jun 08 '21 at 23:14
  • 1
    take care about strtok will change the original string and must be avoided on constant strings, like argv must be – r043v Jun 08 '21 at 23:18
  • 2
    @r043v: [This documentation](https://en.cppreference.com/w/c/language/main_function) states that the `argv` strings are modifiable, and it explicitly states that you can use `strtok` on them. – Andreas Wenzel Jun 08 '21 at 23:21
  • @user3386109 Oh wow, i didn't know you can do that.., yup that's exactly what i need. Thank you – Dennis Jun 08 '21 at 23:21

1 Answers1

2

You can give strtok multiple deliminators:

token = strtok(NULL, ",_");

I guess that will give you:

04 1 03 0 05 1

If that helps?

Otherwise, https://linux.die.net/man/3/strtok_r says strtok_r is the reentrant version.

Personally, I'd probably just do it in two separate steps and avoid nesting it.

Jevon Kendon
  • 545
  • 4
  • 13