什么是在我的呼唤的strlen()在C循环条件最好的选择吗? [英] What is the best alternative to calling strlen() in my for loop condition in C?

查看:115
本文介绍了什么是在我的呼唤的strlen()在C循环条件最好的选择吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读过,这是不好的做法,调用strlen()在我的for循环的条件,因为这是一个O(n)操作。

I've read that it is bad practice to call strlen() in my for loop condition, because this is an O(N) operation.

不过,在看的替代品时,我看到了两个可能的解决方案:

However, when looking at alternatives I see two possible solutions:

int len = strlen(somestring);  
for(int i = 0; i < len; i++)  
{

}

或...

for(int i = 0; somestring[i] != '\0'; i++)  
{

}

现在,第二个选项好像它可能具有的1的优势)不声明一个不必要的变量,和2)应字符串的长度在循环被修改它仍然应该到达终点只要长度不&LT;我。

Now, the second option seems like it might have the advantage of 1) not declaring an unnecessary variable, and 2) should the string length be modified in the loop it should still reach the end as long as the length isn't < i.

不过,我不知道。其中哪一个是C程序员之间的标准做法?

However, I'm not sure. Which one of these is standard practice among C programmers?

推荐答案

第二个通常是preferred。

The second one is usually preferred.

其他流行的形式是

for (char* p = something; *p; p++)
{
   // ... work with *p
}

又一一个是

char* p = something;
char c;
while ((c = *p++))
{
    // ... do something with c
}

(额外的()各地需要分配作出一些可疑的编译器不会发出警告,指出我可能意味着在比较而状态)

(the extra () around assignment are needed to make some suspicious compilers not issue a warning stating I might mean comparison inside while condition)

事实上,的strlen 是相当缓慢的,因为它必须经过整串寻找尾随0,所以,的strlen

Indeed, strlen is quite slow, because it must go through the whole string looking for trailing 0. So, strlen is essentially implemented as

int s = 0;
while (*p++) s++;
return s;

(好吧,其实稍微​​更优化的汇编版本使用)。

(well, in fact a slightly more optimized assembler version is used).

所以,你应该避免使用的strlen 如果可能的话。

So you ought to avoid using strlen if possible.

这篇关于什么是在我的呼唤的strlen()在C循环条件最好的选择吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆