我在这里的第一篇文章(很遗憾我没有早点发现这个伟大的社区)。
无论如何,我编写了一个 C 函数,它从字符串 s 中删除字符串 del 中包含的任何字符。我想知道在速度方面是否有改进的余地,特别是对于查找 del 中包含的字符的部分,在 for 循环内(我使用的是 strpbrk(),但 pmg 明智地建议 strchr ()).
也非常欢迎 Bug 猎手!我认为它很强大,但你永远不知道。
这是代码(提前感谢任何答案)...
当前版本
// remove from string s any char contained in string del (return modified s)
// alg:
// parse s via cp1, keep desired *cp1's by copying them via cp2 to the start of s
// null terminate & return the trimmed s
char *s_strip(char *s, const char *del)
{
char *cp1; // for parsing the whole s
char *cp2; // for keeping desired *cp1's
for (cp1=s, cp2=s; *cp1; cp1++ )
if ( !strchr(del, *cp1) ) // *cp1 is NOT contained in del (thanks pmg!)
*cp2++ = *cp1; // copy it via cp2
*cp2 = 0; // null terminate the trimmed s
return s;
}
原版
char *s_strip(char *s, const char *del)
{
char *cp1; // for parsing the whole s
char *cp2; // for keeping desired *cp1's
for (cp1=s, cp2=s; *cp1; cp1++ )
if ( cp1 != strpbrk(cp1, del) ) { // *cp1 is NOT contained in del
*cp2 = *cp1; // copy it via cp2
cp2++;
}
*cp2 = 0; // null terminate the trimmed s
return s;
}
最佳答案
用 strchr()
代替 strpbrk()
怎么样?
当您只需要检查第一个字符时,您的版本不必要地循环输入字符串。
/* ... */
if (!strchr(del, *cp1)) *cp2++ = *cp1;
/* ... */
关于c - C中的s_strip(s, del)函数,还有比这个更优化的版本吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5860892/