Solsma Dev
Solsma Dev

Reputation: 481

Split C string after identifier

Quick question: I want to split a string literal (a file path) at the last "/".

So, from this: "/folder/new/new2/new3" to this as the result: "/folder/new/new2"

So basically, I always want the result to be one directory behind the absolute path provided.

I've been using strtok something akin to this to get the last directory, but I don't know an easy way to get the second to last directory. :

    char *last
    char *tok = strtok(dirPath, "/");
    while (tok != NULL)
    {
         last=tok;
         tok = strtok(NULL, "/");
    }

Upvotes: 0

Views: 1843

Answers (3)

Alexander V
Alexander V

Reputation: 8698

I have not compiled and run that. Just for fun.

char* p = dirPath, *last = NULL;
for(; *p; p++)
{
   if (*p == '/')
      last = p;
}

if (last)
{
    *last = 0;
    puts(dirPath);
}

Upvotes: 0

Solsma Dev
Solsma Dev

Reputation: 481

In reference to user3121023 's suggestion I used strrchr and then placed a null-terminator in place of the last occurring "/".

char str[] = "/folder/cat/hat/mat/ran/fan";
char * pch;
pch=strrchr(str,'/');
printf ("Last occurence of '/' found at %d \n",pch-str+1);
str[pch-str] = '\0';
printf("%s",str);

This worked perfectly, the result printed is "/folder/cat/hat/mat/ran".

Upvotes: 4

RobP
RobP

Reputation: 9522

Wow am I rusty on straight C, but here goes. A loop similar to your existing code finds the location of the last slash, by using strstr instead of strtok. From there it's just a matter of copying the portion of the string up to that slash. You could also change dirPath in place by overwriting the last slash with a null terminator, but that could lead to memory leaks (?) depending what else your code does...

// find last slash
char *position = strstr(dirPath, "/");
while (strstr(position, "/") != NULL)
{
    position = strstr(position, "/");
}

// now "position" points at the last slash character
if(position) {
    char *answer = malloc(position - dirPath); // difference in POINTERS
    strncpy(answer, dirPath, position - dirPath);
    answer[position - dirPath] = `\0`; // null-terminate the result
}

Upvotes: 0

Related Questions