-1

I get an input with a constant formation. in example:

char* str = "mv /Folder1/folder 2/f1 /Folder1/folder 3"

I need to split it so that i'll end up with two separated string,

str1 == /Folder1/folder 2/f1

str2 == /Folder1/folder 3

I have tried using strtok(str, " /") but it won't work. It ignores the space in the delimiter and only using "/".

Any ideas?

Thank you very much!

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
  • 2
    Possible duplicate of [The most elegant way to iterate the words of a string](https://stackoverflow.com/questions/236129/the-most-elegant-way-to-iterate-the-words-of-a-string) – user0042 Dec 22 '17 at 17:26
  • 1
    Since strtok zaps the delimiter, using slash as the delimiter is flawed. It looks like you need to split on spaces. Personally, I dislike strtok because it damages the input and I’d usually rather my inputs were not mangled. YMMV. – Jonathan Leffler Dec 22 '17 at 17:44
  • Since this question is currently taggedC and the proposed duplicate is strictly C++, it isn’t clear that it’s a good match. – Jonathan Leffler Dec 22 '17 at 17:46

2 Answers2

0

Here is a brief explanation of strtok. When you pass " /" you are telling strtok to split on either a "/" or a " ". In fact, strtok will probably not easily suit your needs since it will not use a pair of chars to split, but will use each char to split. You'll then have to provide logic to reassemble split items that go together but have a space in them. You might be able to do so by looking for the empty token caused by having back to back split chars in " /". That would tell you that you are at the start of a new path string. However, that solution won't be very robust since someone could put in double spaces after mv and break it. Most tools require you to use outer delimiters such as quotes or use "\ " for the space that is part of the filename and path.

Chuck Krutsinger
  • 2,830
  • 4
  • 28
  • 50
0

The second string you pass to strtok isn't a pattern it searches for--it's a set of characters, and it searches for any one item in that set.

In this case, we need to search for a pattern, so we can do the searching with (for one possibility) strstr:

#include <string.h>
#include <stdio.h>

int main() {
    char* str = "mv /Folder1/folder 2/f1 /Folder1/folder 3";

    char *prev = strstr(str, " /");
    char *pos;
    while (NULL != prev) {
        pos = strstr(prev+1, " /");
        printf("%.*s\n", (int)(pos-prev), prev);
        prev = pos;
    }
}
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111