简体   繁体   中英

copy char before /after special operator in c

I have a value in the format of "xxx/yyy" , i used following method to extract the two values before and after "/"

            char * ptr = "xxx/yyy";  

            part2 = strchr( ptr, '/');
            if ( part2 != NULL)
               part2++;

            part1 = strtok(ptr,"/");

Result: part1 = xxx part2 = yyy

This works fine, but when i have the value of ptr like "/yyy" , my result is

       ***part1 = yyy !!!!!! IT should be an empty char!!!!***
       part2 = yyy 

Thanks in advance

The strtok function skips all characters that you pass in the second string. Therefore you get the first string that does not include these characters for the first call. When you need a different behavior you should consider implementing my_strtok() .

#include <stdlib.h>
#include <string.h>
#include <malloc.h>
void main(void)
{
char *a=malloc(strlen(ptr)/2);
char *b=malloc(strlen(ptr)/2);
int i=0;j=0,w;
while(*(ptr+i)!='/') {
*(a+j)=*(ptr+i);
j++; i++;
}
*(a+j)='\0';
j=0;
for(w=i+1;w<=strlen(ptr);w++) {
*(b+j)=*(ptr+w);
j++;
}
printf("pure string : %s \ntoken1 : %s \ntoken2= %s", ptr, a, b);
free(a);
free(b);
}

Harper has already given you the explanation for the behaviour you observe with strtok . Luckily, you have already done the work that strtok would do in your case: You have found the location of the slash. If there's a slash, you could do what strtok would do: Terminate the first string with a zero by overwriting the slash:

int main()
{
    char ptr[] = "xxx/yyy";  
    char *part1, *part2;

    part1 = ptr;
    part2 = strchr(ptr, '/');
    if (part2 != NULL) *part2++ = '\0';

    printf("'%s', '%s'\n", part1, part2);

    return 0;
}

Note that the input string must be modifiable, which your string literal is not. (It happens to be modifiable on your platform, but you should not rely on it; use a char array ptr[] instead of a pointer to a string literal, *ptr .)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM