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

rad*_*r75 8 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 ends on no quote
  // test & return 0 if ends on quote
  return;
}
Run Code Online (Sandbox Code Playgroud)

我想测试字符串是否以引号"结束"

什么是测试这个的好方法?谢谢

R S*_*hko 10

不要忘记确保您的字符串至少包含1个字符:

int testFn(const char *str)
{
    return (str && *str && str[strlen(str) - 1] == '"') ? 0 : 1;
}
Run Code Online (Sandbox Code Playgroud)

  • `(表达)?0:1`是一种有趣的写作方式!!(表达式)`:) (3认同)
  • @caf:也许很有趣,但在这种情况下肯定更具可读性. (2认同)
  • @caf - 我更喜欢`?:`的原因是整个表达式从左到右读取. (2认同)