什么是一个零结尾的字符串,长度 - prefixed字符串克服的问题呢? [英] What are the problems of a zero-terminated string that length-prefixed strings overcome?

查看:1183
本文介绍了什么是一个零结尾的字符串,长度 - prefixed字符串克服的问题呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是一个零结尾的字符串的问题,长度 - prefixed字符串克服?

What are the problems of a zero-terminated string that length-prefixed strings overcome?

我在读这本书撰写大code卷。 1,我不得不考虑这个问题。

I was reading the book Write Great Code vol. 1 and I had that question in mind.

推荐答案

一个问题是零结尾的字符串,你必须保持反复查找字符串的结尾。经典的例子,这是低效被串联成一个缓冲区:

One problem is that with zero-terminated strings you have to keep finding the end of the string repeatedly. The classic example where this is inefficient is concatenating into a buffer:

char buf[1024] = "first";
strcat(buf, "second");
strcat(buf, "third");
strcat(buf, "fourth");

在每次调用 strcat的程序必须从字符串的开头开始并找到终结者知道从哪里开始追加。这意味着功能花费越来越多的时间寻找追加为字符串变长的地方。

On every call to strcat the program has to start from the beginning of the string and find the terminator to know where to start appending. This means the function spends more and more time finding the place to append as the string grows longer.

随着长度 - prefixed字符串 strcat的功能相当于将知道到底是马上,并追加到后只会更新长度。

With a length-prefixed string the equivalent of the strcat function would know where the end is immediately, and would just update the length after appending to it.

有利弊,再presenting串的每方式以及他们是否会导致问题为你取决于你用​​绳子做什么,哪些业务需要是有效的。上述的问题可以通过改变code可以避免的性能成本手动跟踪的字符串的末尾,因为它的增长,所以可以克服。

There are pros and cons to each way of representing strings and whether they cause problems for you depend on what you are doing with strings, and which operations need to be efficient. The problem described above can be overcome by manually keeping track of the end of the string as it grows, so by changing the code you can avoid the performance cost.

这篇关于什么是一个零结尾的字符串,长度 - prefixed字符串克服的问题呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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