如何有效地计算在C字符串的长度? [英] How to calculate the length of a string in C efficiently?

查看:135
本文介绍了如何有效地计算在C字符串的长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何计算在C字符串的有效长度(时间)?

How to calculate the length of a string in C efficiently (in time)?

现在我做的:

int calculate_length(char *string) {
    int length = 0;
    while (string[length] != '\0') {
        length++;
    }
    return length;
}

不过相比的strlen()例如它的速度很慢,有没有其他的办法做到这一点?

But it's very slow compared to strlen() for example, is there any other way to do it?

感谢。

编辑:我在一个独立的环境中工作,我不能使用任何外部的lib包括string.h中

推荐答案

的FreeBSD来源$ C ​​$ C

size_t
strlen(const char *str)
{
    const char *s;
    for (s = str; *s; ++s);
    return(s - str);
}

相比于你的code

,这可能映射非常漂亮的一个汇编指令,它可以解释一个很大的性能差异。

Compared to your code, this probably maps very nicely to an assembler instruction, which can explain a big performance difference.

这篇关于如何有效地计算在C字符串的长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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