-1

I have a string like "123-#-#-abc-user-#-#-abcpassword-#-#-123456", i need to split this string with pattern "-#-#-" to create an array. I used the following code to do this

    char buf[5000];
    strcpy(buf, "123-#-#-abc-user-#-#-abcpassword-#-#-123456");
    int i = 0;
    char *p = strtok (buf, "-#-#-");
    char *array[5000];

    int items = 0;
    while (p != NULL)
    {
        items++;
        array[i++] = p;
        p = strtok (NULL, "-#-#-");
    }

But the result isn't getting for "123-#-#-abc-user-#-#-abcpassword-#-#-123456" due to the hyphen in the "abc-user". What i am expecting is that array[0] has the 123, array[1] has abc-user, array[2] as abcpassword etc. Is there any other method to split to array with the exact pattern ?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Dev
  • 69
  • 8
  • 1
    read the manuel of `strtok()`, it's only match character not string ! – Stargateur Dec 08 '17 at 10:00
  • 1
    In [`strtok()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/strtok.html) the second argument `"-#-#-"` means: 'tokenize on "-" **or** "#" **or** "-" **or** "#" **or** "-"'. Use another function, eg [`strstr()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/strstr.html). – pmg Dec 08 '17 at 10:02

1 Answers1

4

strtok() here will not produce the exact output you expect. Check the details, C11, chapter §7.24.5.8

A sequence of calls to the strtok function breaks the string pointed to by s1 into a sequence of tokens, each of which is delimited by a character from the string pointed to by s2. [...]

So, presence of any character of the whole delimiter string will cause tokenization.

You need to look for strstr() which searches for a sub string inside a bigger string. Once again, from C11, chapter 7.24.5.7

char *strstr(const char *s1, const char *s2);

The strstr function locates the first occurrence in the string pointed to by s1 of the sequence of characters (excluding the terminating null character) in the string pointed to by s2.

and

The strstr function returns a pointer to the located string, or a null pointer if the string is not found. [...]

So you can

  • use the function call,
  • take the non-null returned pointer
  • perform pointer arithmetic to reach to the next token you want.
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261