faster strlen?

后端 未结 8 2176
小鲜肉
小鲜肉 2021-02-20 15:49

Typical strlen() traverse from first character till it finds \\0. This requires you to traverse each and every character. In algorithm sense, its O(N).

8条回答
  •  没有蜡笔的小新
    2021-02-20 16:12

    The short answer: no.

    The longer answer: do you really think that if there were a faster way to check string length for barebones C strings, something as commonly used as the C string library wouldn't have already incorporated it?

    Without some kind of additional knowledge about a string, you have to check each character. If you're willing to maintain that additional information, you could create a struct that stores the length as a field in the struct (in addition to the actual character array/pointer for the string), in which case you could then make the length lookup constant time, but would have to update that field each time you modified the string.

提交回复
热议问题