2014-10-18 3 views
1

Скажут, у меня есть константный символ * строка, как это:Получить подстроку строки с помощью C

../products/product_code1233213/image.jpg 

Я хочу, чтобы получить вторую последнюю часть пути строки, которая является именем родительской папки файла JPG , как бы я это сделал?

+0

Это может быть полезно: http://stackoverflow.com/questions/9210528/split-string-with-delimiters-in-c – Ruslan

ответ

2

Вы можете использовать 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); 
} 

Выход:

products 
product_code1233213 
image.jpg 
+0

испытано, и работал, спасибо большое! – dulan

+0

Вы не можете использовать 'strtok()' в константной строке. – potrzebie

+0

@Jayesh Его вопрос сказал, что это 'const char *', который является постоянной строкой ... – Ruslan

1

Эта версия работает с 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; 
} 
0

Использование только strchr() и не откаты. Быстрый и const -сухо.

#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; 
} 
Смежные вопросы