连接字符串的问题 [英] Problems concatenating strings

查看:93
本文介绍了连接字符串的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




我正在解决一个问题,我需要实现一个字符串缓冲区

我可以从一个删除一个任意长度的char *结束并将它们添加到

另一个。


到目前为止,我想到完成此任务的唯一方法是

创建使用


新char [length];


和strcopy,strcat函数用
$重新填充char数组b $ b每次从头/尾添加/删除字节时需要的数据量

字符串。


有没有更有效的方法实现我所要求的行为?


非常感谢


Lawrie

解决方案

如果你总是要从一端移除并从

中添加其他,那么使用std :: queue< char>。如果您需要任意访问,请使用

std :: vector< char> ;.


-Brian


blockquote>

尝试环形缓冲区。


#define BUFFER_SIZE 4096

#define INDEX_MASK(BUFFER_SIZE-1)

char buffer [BUFFER_SIZE];

int head_index,tail_index;


void push_front(char ch){

buffer [head_index] = ch;

head_index =(head_index + 1)& INDEX_MASK;

}


char pop_back(){

char ch = buffer [tail_index];

tail_index =(tail_index + 1)& INDEX_MASK;

}


void copy_from_front_to_back(int n){

while(n - > 0){

push_front(pop_back());

}

}


>> #define BUFFER_SIZE 4096


原始帖子没有说缓冲器需要多大,

因此最好假设一个任意大小,而你的代码却没有。
因为你正在使用bitwize&如果你将BUFFER_SIZE更改为除了

2之外的其他任何东西,你的代码将会破坏你的代码将被破坏。它也会破坏你的代码如果你push_front()更多

字符比BUFFER_SIZE(你的代码没有检查。)

这正是为什么它更好地使用容器在标准的

库中。


-Brian


Hi,

I am working on a problem where I need to implement a string buffer
that I can remove an arbitary length char* from one end and add them to
the other.

So far the only way I have thought of to accomplish this task involves
creating using

new char[length];

and the strcopy,strcat functions to repopulate the char array with the
required amount of data each time I add/remove bytes from the head/tail
of the string.

Is there a more efficient method of implementing my required behaviour?

Many thanks

Lawrie

解决方案

If you''re always going to be removing from one end and adding from the
other, then use std::queue<char>. If you need arbitrary access, use
std::vector<char>.

-Brian


Try ring buffer.

#define BUFFER_SIZE 4096
#define INDEX_MASK (BUFFER_SIZE-1)
char buffer[BUFFER_SIZE];
int head_index,tail_index;

void push_front(char ch) {
buffer[head_index]=ch;
head_index=(head_index+1)&INDEX_MASK;
}

char pop_back() {
char ch=buffer[tail_index];
tail_index=(tail_index+1)&INDEX_MASK;
}

void copy_from_front_to_back(int n) {
while(n-->0) {
push_front(pop_back());
}
}


>>#define BUFFER_SIZE 4096

The original post said nothing about how big the buffer needed to be,
thus it''s best to assume an arbitrary size, which your code does not.
Since you''re using the bitwize & to do the wrap around of your indices,
your code will break if you change BUFFER_SIZE to anything other than a
power of 2. It''s also going to break if you push_front() more
characters than BUFFER_SIZE ( which you''re code doesn''t check for. )
This is exactly why its better to use the containers in the standard
library.

-Brian


这篇关于连接字符串的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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