Reputation: 194
I am writing a very simple function in C to check if a string is an absolute path or relative path. No matter what I try it is always returning false.
Here is what I have tried:
int isAbsolute(char *str){
if(strcmp(str,"/")){
return 1;
}
return 0;
}
and I call it like:
printf("%d\n", isAbsolute("/"));
which is returning false every time. Clearly I am missing something obvious but I haven't been able to figure it out...
Upvotes: 3
Views: 16099
Reputation: 6437
strcmp
compares the whole string, so your function will only return true
if the string you're passing is "/".
You can look at strncmp instead:
if(strncmp(str,"/", 1)) ...
or compare only one character:
(if (str[0] == '/')) ...
Upvotes: 4
Reputation: 2166
Similarly to strncmp
you can use memcmp
which has the number of bytes to compare as an argument:
int isAbsolute(const char *str){
if (0 == memcmp(str, "/", 1){
return 1;
} else {
return 0;
}
}
Don't forget that return value $0$ means equality. In your code you return 0 in that case which is probably not as you intended.
Upvotes: 2
Reputation: 49
Strcmp return value is zero on success case ,that's why it is not going to true
Upvotes: 0
Reputation: 1439
Don't have access to a compiler, but I think this will work because C-style strings are just arrays with a termination character:
int isAbsolute(const char *str){
return (str[0] == '/');
}
Upvotes: 6
Reputation: 12749
As was pointed out, strcmp
only matches if the strings being compared are of the same length.
To compare a single character at the front of the string, you can just do:
int isAbsolute(const char *str) {
return (str[0] == '/');
}
If the prefix you are looking for is longer than one character, then this might help. I like Fred Foo's answer better than the one that got accepted (as did a majority of voters).
Upvotes: 3