strlen的C和C ++:它是如何工作的? [英] strlen in C and C++ : how does it work?

查看:128
本文介绍了strlen的C和C ++:它是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何的strlen()内部工作?以及是否有任何固有缺陷的功能?

How does strlen() work internally? And are there any inherent bugs in the function?

推荐答案

的strlen 通常是通过在一个字符串,直到 \\ 0计数的人物作品字符被发现。一个典型的实现将是:

strlen usually works by counting the characters in a string until a \0 character is found. A canonical implementation would be:

size_t strlen (char *str) {
    size_t len = 0;
    while (*str != '\0') {
        str++;
        len++;
    }
    return len;
}

有在功能没有固有的缺陷,它的工作原理完全一样记录。

There is no inherent bug in the function, it works exactly as documented.

这并不是说就没有问题,即:

That's not to say it doesn't have problems, to wit:


  • 如果你传递一个串不具有 \\ 0 末,你可能会碰到的问题,但是从技术上来说,这不是一个C字符串< SUP>(一),这是你自己的错。

  • 您不能把 \\ 0 在字符串中的字符,但再次,它不会在这种情况下,C字符串。

  • 这不是最有效的方式 - 你可以存储一个长度可达前面,这样你可以得到的长度更快

  • if you pass it a "string" that doesn't have a \0 at the end, you may run into problems but technically, that's not a C string (a) and it's your own fault.
  • you can't put \0 characters in your string but, again, it wouldn't be a C string in that case.
  • it's not the most efficient way - you could store a length up front so you could get the length much quicker.

但这些都不是错误,他们只是一个设计决策的后果。

But none of those are bugs, they're just consequences of a design decision.

另请参见由Joel Spolsky的这个优秀的文章,他在那里讨论了各种字符串格式及其特征,包括普通的C字符串,字符串帕斯卡尔和两者的结合,空终止字符串帕斯卡,虽然他有一个更,应我们说,他们多彩一词: - )

See also this excellent article by Joel Spolsky where he discusses various string formats and their characteristics, including normal C strings, Pascal strings and the combination of the two, null terminated Pascal strings, though he has a more, shall we say, "colorful" term for them :-)

(一) C字符串被定义为随后是一系列的非终止字符(即比其他任何\\ 0 )终止符。因此,这一定义不允许的顺序和序列中都嵌入终结没有这样一个终止符。

(a) A C string is defined as a series of non-terminator characters (ie, any other than \0) followed by that terminator. Hence this definition disallows both embedded terminators within the sequence and sequences without such a terminator.

或者,把它更简洁(根据ISO标准):

Or, putting it more succinctly (as per the ISO standard):

一个字符串是由终止字符的连续序列与包括第一个空
  性格。

A string is a contiguous sequence of characters terminated by and including the first null character.

这篇关于strlen的C和C ++:它是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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