检查字符串的最后一个字符用C

问题描述:

如果我有两种类型的字符串为:检查字符串的最后一个字符用C

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; 
} 

我想测试字符串是否以引号结束“或不

这将是一个很好的测试这种方式感谢

+5

你应该改变'int testFn(const char * str)' – 2010-04-07 21:31:42

+0

非常感谢大家! – radar75 2010-04-07 21:33:37

+1

不要忘记接受一个答案! ;-) – slacker 2010-04-07 21:50:10

不要忘记,以确保您的字符串具有至少1个字符:

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

您得到的结果相反。检查OP给出的规格。 – slacker 2010-04-07 21:42:14

+0

@slacker - 是的,我注意到在写完它之后,我已经用'?:' – 2010-04-07 21:46:53

+2

'(表达式)更新了我的示例? 0:1'是一种有趣的写作方式'!(表达式)':) – caf 2010-04-07 22:05:04

int testFn(const char *str) 
{ 
    return !str || !*str || str[strlen(str) - 1] != '\"'; 
} 
+2

不正确处理长度为0的字符串。 – 2010-04-07 21:36:03

+0

可能导致空字符串崩溃 – slacker 2010-04-07 21:36:51

int testFn(const char *str) 
{ 
    if(*str && str[strlen(str + 1)] == '"') 
    return 0; 
    else 
    return 1; 
} 
+0

你的空指针崩溃;-) – 2010-04-07 21:42:55

+0

@PéterTörök:当然可以。不要把它传递给这个函数,然后:)。 – slacker 2010-04-07 21:44:52

+0

如果你不传递一个零长度的字符串,我不会传递一个空指针给你的,好吗? :-) – 2010-04-07 21:55:58

零长度字符串...不是字符串,与数字相同 - 我不在乎您如何定义它。空指针需要自己的处理,因为它们是它们自己的类别。有愚蠢的指针返回移植,但他们只会带你到目前为止。你必须定义一切。我从空指针开始,因为NOTHING处理它们。等等... Python的确如此。也许你在错误的论坛上。

现在我需要找到我的段错误功能。我知道我写了它,因为它保留了众生 - 我找不到它。

+0

这不提供问题的答案。一旦你有足够的[声誉](https://stackoverflow.com/help/whats-reputation),你将可以[对任何帖子发表评论](https://stackoverflow.com/help/privileges/comment);相反,[提供不需要提问者澄清的答案](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-c​​an- I-DO-代替)。 - [来自评论](/ review/low-quality-posts/18842954) – 2018-02-16 19:07:10