如何检查是否字符串在C另一个字符串开始? [英] How to check if a string starts with another string in C?
本文介绍了如何检查是否字符串在C另一个字符串开始?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有什么样 startsWith(str_a,str_b)
中的标准C库?
它应该采取指针与nullbytes结束两个字符串,并告诉我是否第一个也是在第二个的开始完全出现。
例如:
ABC,ABCDEF - >真正
ABCDEF,ABC - >假
ABD,abdcef - >真正
ABC,ABC - >真正
解决方案
显然,有这种没有标准的C函数。所以:
布尔startsWith(为const char * pre,为const char *海峡)
{
为size_t LEN pre = strlen的(pre)
lenstr = strlen的(STR);
返回lenstr< LEN pre?假:STRNCMP(pre,STR,LEN pre)== 0;
}
Is there something like startsWith(str_a, str_b)
in the standard C library?
It should take pointers to two strings that end with nullbytes, and tell me whether the first one also appears completely at the beginning of the second one.
Examples:
"abc", "abcdef" -> true
"abcdef", "abc" -> false
"abd", "abdcef" -> true
"abc", "abc" -> true
解决方案
Apparently there's no standard C function for this. So:
bool startsWith(const char *pre, const char *str)
{
size_t lenpre = strlen(pre),
lenstr = strlen(str);
return lenstr < lenpre ? false : strncmp(pre, str, lenpre) == 0;
}
这篇关于如何检查是否字符串在C另一个字符串开始?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文