标准C库中有没有类似startsWith(str_a, str_b)
的东西?
它应该采用指向两个以空字节结尾的字符串的指针,并告诉我第一个是否也完全出现在第二个字符串的开头。
例子:
"abc", "abcdef" -> true
"abcdef", "abc" -> false
"abd", "abdcef" -> true
"abc", "abc" -> true
最佳答案
这个没有标准函数,但是你可以定义
bool prefix(const char *pre, const char *str)
{
return strncmp(pre, str, strlen(pre)) == 0;
}
我们不必担心 str
比 pre
短,因为根据 C 标准 (7.21.4.4/2):
The
strncmp
function compares not more thann
characters (characters that follow a null character are not compared) from the array pointed to bys1
to the array pointed to bys2
."
关于c - 如何检查一个字符串是否以C中的另一个字符串开头?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4770985/