In my current code, I am trying to pass in a file path, separate the file path by "/"
, and then checking through each delimited value against every element in an array named categories
using a for loop. If any element in the array matches as a substring using strstr()
, it will return the value of the element, if not it will return "Others"
.
I managed to produce the output that I want, however I realise that whenever there is an even number of elements in categories array, the output will be 1 of the value from the file path such as
If the file path is
"/a/b/Lib/Contact/c"
If the categories are
char *categories[] = {"Library","Applications","Contact","dsdfd"};
the output will be b
.
Here is my code for your reference:
const char *categorize(char*path)
{
int i = 0;
char str[1024];
char *token;
char *delim = "/";
char *categories[] = {"Library","Applications","Contact","dsdfd"};
bool check = false;
strcpy(str,path);
token = strtok(str,delim);
while (token !=NULL)
{
if(check == true)
break;
//printf("%s\n",token);
for (i = 0; i <(sizeof(categories)/sizeof(char*)); i++)
{
if(categories[i] == NULL)
break;
if(strstr(token, categories[i]))
{
check = true;
break;
}
}
token = strtok (NULL, delim);
}
if (check == true)
return "Others";
else
return categories[i];
}
Edit: I have encountered another problem. I tried using a test case if the file path does not contain any substring. It should return "Others", however it is returning me "/".
Edit2: I have sort of solved the problem by changing the if statement to check == true
. However, I realise that my code here is not good which @LưuVĩnhPhúc and @fasked mentioned in the comments and I would hope to possibly fixed it.