1

Say I have a const char* string like this:

../products/product_code1233213/image.jpg

I want to retrieve the second last part of this path string, which is the parent folder name of the jpg file, how would I do that?

1

3 Answers 3

2

You can use strtok.

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

int main()
{
   char str[] = "/products/product_code1233213/image.jpg";
   char s[2] = "/";
   char *token;

   /* get the first token */
   token = strtok(str, s);

   /* walk through other tokens */
   while( token != NULL ) 
   {
      printf( " %s\n", token );

      token = strtok(NULL, s);
   }

   return(0);
}

Output:

products
product_code1233213
image.jpg
Sign up to request clarification or add additional context in comments.

3 Comments

You can't use strtok() on a constant string.
@Ruslan this is called string literal and yes it's illegal to modify it.But any way OP have happy with this solution.
I did make a little tweak to make it work, by strcpy to a char*
1

This version works with a const char *:

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

int main()
{
    const char *s = "/products/product_code1233213/image.jpg";
    const char *p = s, *begin = s, *end = s;
    char *result;
    size_t len;

    while (p) {
        p = strchr(p, '/');
        if (p) {
            begin = end;
            end = ++p;
        }
    }
    if (begin != end) {
        len = end - begin - 1;
        result = malloc(len + 1);
        memcpy(result, begin, len);
        result[len] = '\0';
        printf("%s\n", result);
        free(result);
    }
    return 0;
}

Comments

0

Using only strchr() and no backtracking. Fast and const-safe.

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

#define SEPARATOR '/'

const char *path = "../products/product_code1233213/image.jpg";

int main(void) {
    const char *beg, *end, *tmp;

    beg = path;
    if ((end = strchr(beg, SEPARATOR)) == NULL) {
        exit(1); /* no separators */
    }
    while ((tmp = strchr(end + 1, SEPARATOR)) != NULL) {
        beg = end + 1;
        end = tmp;
    }
    (void) printf("%.*s\n", (int) (end - beg), beg);
    return 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.