c - Extracting the string from the delimiter "/" -
#include<stdio.h> #include<malloc.h> #include<string.h> int main(){ char* path = "lost+found/d1/dentry"; char* str = malloc(100); char *temp; if(null == str) perror("malloc failed"); temp = str; while(*path != '/'){ *str++ = *path++; } *str = '\0'; str = temp; printf("\n str : %s \n",str); return 0; }
o/p:
str : lost+found
is there library function can extract string delimiter "/" [strrchr , srchr gives last , first occurences of '/', string search lost+found].
strtok direct way c library has offer tokenize string. there glitches though:
- the string want tokenize cannot const
- the given string changed during
strtok
calls
if need first segment in path (as question suggests) , not '/'-delimited tokens strchr may come in handy (along strcpy , pointer arithmetic).
Comments
Post a Comment