cstrcmpstrncmp

Checking the first letter of a string in c


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...


Solution

  • 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] == '/');
    }