我有一个程序可以删除字符串中的所有变量。这些变量以“$”开头。因此,举例来说,如果我给出一个像 [1,2,$1,$2] 这样的字符串,它应该只返回 [1,2]。
但是,哪个循环对性能更好?
这个:
while (token != NULL)
{
if (*token != '$')
{
sprintf(dst, "%s,%s", dst, token);
}
token = strtok(NULL, "], ");
}
或者这个:
while (token != NULL)
{
if (*token != '$')
{
strcat(dst, token);
strcat(dst, ",");
}
token = strtok(NULL, "], ");
}
最佳答案
根据 C11 standard 7.21.6.6 p2 , 描述 sprintf
:
If copying takes place between objects that overlap, the behavior is undefined.
所以您的第一个代码片段在从 dst
复制到 dst
时调用未定义的行为。 strcat
方法没有这个问题。
关于c - 循环内的 strcat() 与 sprintf(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50416150/