3 c
库函数strspn的定义是:
size_t strspn(const char *str, const char *chars)
/* Return number of leading characters at the beginning of the string `str`
which are all members of string `chars`. */
Run Code Online (Sandbox Code Playgroud)
例如,如果'str'是"fecxdy"而'chars'是"abcdef"那么函数将返回3,因为'f','e'和'c'都出现在'chars'中的某个地方,给出3个前导字符' str'和'x'是'str'的第一个字符,它不是'chars'的成员.
有人可以帮我写一个'C'中的strspn实现.我可以从实现中调用的唯一库函数是strlen.
基本思想是逐步遍历字符串,一次一个字符,并测试它是否在字符集中.如果不是,请停止并返回答案.在伪代码中,它看起来像:
count = 0
for each character c in str
if c is not in chars
break
count++
return count
Run Code Online (Sandbox Code Playgroud)
该if c is not in chars测试可以通过所有的字符迭代实现chars和测试,如果c匹配任何字符.请注意,这不是最快的实现,因为它涉及单步执行chars每个字符的字符串str.更快的实现将使用查找表来测试是否c is not in chars.