i've been trying to figure this out for a while now and i have absolutely no clue how to fix this. I have a pretty decent sized project and i'm using strtok countless times wihout any problems but it's not working here. Please Help :(
Edit: i was looking for prefix removal and not strtok. I'm leaving this here if someone is confused and googles this.
This is the code in question:
#include <stdio.h>
#include <string.h>
int main()
{
char root[1000];
char home[1000];
strcpy(root,"/Users/me/Desktop/my-project"); // this is working
strcpy(home,"/Users/me/Desktop/my-project/home"); // this is working
strtok(home,root); // here's the problem
printf("%s",home);
}
Result 1:
/Users/me/Desktop/my-project/h
I've also tried:
char *ptr = strtok(home,root);
printf("%s",ptr);
Result 2:
h
Shouldn't both return /home
?
as @paxdiablo pointed out and as i was using it in my entire project (i haven't slept so forgive me), strtok(char * str, char * delimiters)
takes a list of delimiters.
What i was actually trying to do was remove the root
substring from the home
string.
Since they will always start with the same substring /Users/me/Desktop/my-project
, i can find the part unique to home
right after root
ends and that can be done like this really easily:
#include <stdio.h>
#include <string.h>
int main()
{
char root[1000];
char home[1000];
strcpy(root,"/Users/mbp/Desktop/my-project");
strcpy(home,"/Users/mbp/Desktop/my-project/home");
int n = strlen(root); // length of the root string
// where to copy, from where to start copying, how many to copy
strncpy(home, home + n ,strlen(home)-1);
printf("%s",home);
}
So what i do is:
home[n]
to home[strlen(home)-1]
Result:
/home