tags:

views:

99

answers:

3

If I have two types of strings as:

const char *str1 = "This is a string with \"quotes escaped at the end\""; 
const char *str2 = "This is a \"string\" without quotes at the end"; 

testFn(str1);
testFn(str2);

int testFn(const char *str)
{
  // test & return 1 if ends on no quote
  // test & return 0 if ends on quote
  return;
}

I would like to test if the string ends with a quote " or not

What would be a good way of testing this? Thanks

+4  A: 
int testFn(const char *str)
{
  return !str || !*str || str[strlen(str) - 1] != '\"';
}
Péter Török
Doesn't handle 0-length string correctly.
David Gelhar
Could crash on an empty string
slacker
+7  A: 

Don't forget to make sure your string has at least 1 character:

int testFn(const char *str)
{
    return (str && *str && str[strlen(str) - 1] == '"') ? 0 : 1;
}
R Samuel Klatchko
You got the result reversed. Check the specification given by OP.
slacker
@slacker - yes, I noticed that after I wrote it but I already updated my example with a `?:`
R Samuel Klatchko
`(expression) ? 0 : 1` is a funny way of writing `!(expression)` :)
caf
@caf:Maybe funny, but in this case definitely more readable.
slacker
@caf - the reason I prefer `?:` is that the entire expression reads left to right.
R Samuel Klatchko
+1  A: 
int testFn(const char *str)
{
  if(*str && str[strlen(str + 1)] == '"')
    return 0;
  else
    return 1;
}
slacker
Yours crashes on null pointer ;-)
Péter Török
@Péter Török: Sure it does. Don't pass it to this function, then :).
slacker
If you don't pass a zero-length string to mine, I won't pass a null pointer to yours, OK? :-)
Péter Török
@Péter Török:A zero-length string is a correct string. A NULL pointer does **not** describe a correct string. Passing it as an argument here violates the input specification.I hate unnecessary checks, they kill performance (when they pile up).
slacker
Hey, this was a joke, please don't take it as nit picking...
Péter Török
@Péter Török:I didn't. Just setting some things straight for other readers :-). I *do* believe that a NULL check is unnecessary in this case.
slacker