Checking the first letter of a string in c

14.8k views Asked by At

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

5

There are 5 answers

2
Billy Ferguson On BEST ANSWER

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] == '/');
}
0
Henno Brandsma On

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.

0
rohit On

Strcmp return value is zero on success case ,that's why it is not going to true

0
pat On

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

0
AntonH On

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] == '/')) ...