检查c中字符串的最后一个字符

检查c中字符串的最后一个字符,c,string,C,String,如果我有两种类型的字符串: 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 end

如果我有两种类型的字符串:

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;
}
我想测试字符串是否以引号结尾


测试这个的好方法是什么?谢谢你别忘了确保你的字符串至少有一个字符:

int testFn(const char *str)
{
  return !str || !*str || str[strlen(str) - 1] != '\"';
}
int testFn(const char *str)
{
    return (str && *str && str[strlen(str) - 1] == '"') ? 0 : 1;
}

您应该将其更改为
int testFn(const char*str)
可能会在空字符串上崩溃
(表达式)?0:1
是编写
(表达式)的有趣方式
:)@caf:也许很有趣,但在这种情况下,它肯定更具可读性。@caf-我更喜欢
?:
的原因是整个表达式从左到右读取。@Péter Török:长度为零的字符串是正确的字符串。空指针不能描述正确的字符串。在这里将其作为参数传递违反了输入规范。我讨厌使用空指针必要的检查会扼杀性能(当它们堆积起来时)。@Péter Török:我没有。只是为其他读者澄清了一些事情:-)。我确实认为在这种情况下,空检查是不必要的。
int testFn(const char *str)
{
  if(*str && str[strlen(str + 1)] == '"')
    return 0;
  else
    return 1;
}