如何比较字符串的两端用C? [英] How to compare ends of strings in C?
本文介绍了如何比较字符串的两端用C?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要确保我的字符串.foo此时已经结束。我使用C,我完全不熟悉的语言。我发现做到这一点,最好的办法如下。任何C大师想确保我典雅,并明智地这样做呢?
INT EndsWithFoo(字符*海峡)
{
如果(strlen的(STR)> = strlen的(富))
{
如果(STRCMP(STR +的strlen(STR) - strlen的(富),包含.foo))
{
返回1;
}
}
返回0;
}
解决方案
不要调用strlen不止一次每串。
INT的endsWith(为const char * str中,为const char *后缀)
{
如果(!STR ||!后缀)
返回0;
为size_t lenstr = strlen的(STR);
为size_t lensuffix = strlen的(后缀);
如果(lensuffix> lenstr)
返回0;
返回STRNCMP(STR + lenstr - lensuffix,后缀,lensuffix)== 0;
}INT EndsWithFoo(为const char * STR){返回的endsWith(STR,包含.foo); }
编辑:为迂腐添加NULL检查。对于超迂腐,讨论是否应该返回非零值,如果这两个海峡和后缀都是NULL。
I want to make sure my string ends with ".foo". I am using C, a language I am not totally familiar with. The best way I have found to do it is below. Any C gurus want to make sure I'm doing this elegantly and wisely?
int EndsWithFoo(char *str)
{
if(strlen(str) >= strlen(".foo"))
{
if(!strcmp(str + strlen(str) - strlen(".foo"), ".foo"))
{
return 1;
}
}
return 0;
}
解决方案
Don't call strlen more than once per string.
int EndsWith(const char *str, const char *suffix)
{
if (!str || !suffix)
return 0;
size_t lenstr = strlen(str);
size_t lensuffix = strlen(suffix);
if (lensuffix > lenstr)
return 0;
return strncmp(str + lenstr - lensuffix, suffix, lensuffix) == 0;
}
int EndsWithFoo(const char *str) { return EndsWith(str, ".foo"); }
EDIT: added NULL check for the pedantic. For the ultra pedantic, debate whether it should return non-zero if both str and suffix are both NULL.
这篇关于如何比较字符串的两端用C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文