the*_*ejh 73 c string comparison startswith
startsWith(str_a, str_b)标准C库中有类似的东西吗?
它应该指向两个以nullbytes结尾的字符串,并告诉我第一个字符串是否也完全出现在第二个字符串的开头.
例子:
"abc", "abcdef" -> true
"abcdef", "abc" -> false
"abd", "abdcef" -> true
"abc", "abc" -> true
Run Code Online (Sandbox Code Playgroud)
Fre*_*Foo 130
这没有标准功能,但您可以定义
bool prefix(const char *pre, const char *str)
{
return strncmp(pre, str, strlen(pre)) == 0;
}
Run Code Online (Sandbox Code Playgroud)
我们不必担心str比pre根据C标准(7.21.4.4/2)更短:
的
strncmp函数比较不大于n字符从阵列指向(即跟随一个空字符不进行比较字符)s1到阵列指向s2".
T.J*_*der 65
显然,没有标准的C功能.所以:
bool startsWith(const char *pre, const char *str)
{
size_t lenpre = strlen(pre),
lenstr = strlen(str);
return lenstr < lenpre ? false : memcmp(pre, str, lenpre) == 0;
}
Run Code Online (Sandbox Code Playgroud)
请注意,上面的内容很好而且清晰,但是如果你是在一个紧凑的循环中或者使用非常大的字符串,它可能无法提供最佳性能,因为它会在前面(strlen)扫描两个字符串的全长.像wj32或者Christoph这样的解决方案可能会提供更好的性能(虽然这个关于矢量化的评论超出了我的C).另请注意Fred Foo的解决方案,它避免strlen了str(他是对的,没有必要).只对(非常)大字符串或在紧密循环中重复使用有关,但是当它重要时,它很重要.
Chr*_*oph 32
我可能会去strncmp(),但只是为了一个原始实现的乐趣:
_Bool starts_with(const char *restrict string, const char *restrict prefix)
{
while(*prefix)
{
if(*prefix++ != *string++)
return 0;
}
return 1;
}
Run Code Online (Sandbox Code Playgroud)
我不是写优雅代码的专家,但......
int prefix(const char *pre, const char *str)
{
char cp;
char cs;
if (!*pre)
return 1;
while ((cp = *pre++) && (cs = *str++))
{
if (cp != cs)
return 0;
}
if (!cs)
return 0;
return 1;
}
Run Code Online (Sandbox Code Playgroud)
小智 5
使用strstr()功能. Stra == strstr(stra, strb)