java的StringBuffer用起来很方便,我用C语言也实现了类似效果

#include <stdio.h>
#include <string.h>

/*
使用C语言实现类似java的StringBuffer效果

风的影子 编写
2019-11-09 
*/
typedef struct STRING_BUFFER{
    char *name; //结构体名字 
    char *text; //文字 
    int len; //文字长度
    char *coding; //文本编码 
    int ram_len; //申请的内存容量 
} STRING_BUFFER;

#define CODING_GBK "GBK"
#define CODING_UTF8 "UTF-8"
#define CODING_UNICODE "UTF-16"

/*
创建一个buffer 
*/
STRING_BUFFER *create_buffer(){
    STRING_BUFFER *buffer = malloc(sizeof(STRING_BUFFER));
    memset(buffer,0,sizeof(STRING_BUFFER));
    buffer->name= "STRING_BUFFER";
    buffer->ram_len= 16;
    buffer->text = malloc(buffer->ram_len);
    buffer->coding = CODING_GBK;

    return buffer;
}

//向buffer中添加GBK编码文字
void buf_append_gbk(STRING_BUFFER *buffer, char *text,int len){
    if(buffer->len+len+2 >= buffer->ram_len){
        char *temp=buffer->text;

        buffer->ram_len*=2;
        buffer->text = malloc(buffer->ram_len);
        memcpy(buffer->text,temp, buffer->len);
        free(temp);
    }
    char *ptr = buffer->text+buffer->len;
    memcpy(ptr, text, len);
    buffer->len+=len;

}

//向buffer中添加UTF-8编码文字
void buf_append_utf(STRING_BUFFER *buffer,char *utf,int len){

}

//向buffer中添加unicode编码文字 
void buf_append_uni(STRING_BUFFER *buffer,char *text,int len){

}

//获取buffer的GBK编码文字 获取的文字需要释放内存 
char* buf_togbkstring(STRING_BUFFER *buffer){
    char *retext = NULL;
    if(strcmp(buffer->coding,CODING_GBK)==0){
        retext = malloc(buffer->len+1);
        memcpy(retext, buffer->text, buffer->len);
        *(retext+buffer->len) = 0;
    }
    return retext;
}

//获取buffer的utf编码文字 获取的文字需要释放内存 
char* buf_toutfstring(STRING_BUFFER *buffer){

}

//获取buffer的unicode编码文字  获取的文字需要释放内存 
char* buf_tounistring(STRING_BUFFER *buffer){

}

//释放内存
int buf_free(STRING_BUFFER *buffer){
    free(buffer->text);
    free(buffer);
    return 0;
} 

int main(int argc, char *argv[])
{
    STRING_BUFFER *buffer = create_buffer();
    char *text = "风的影子 ";

    buf_append_gbk(buffer,text, strlen(text));
    buf_append_gbk(buffer,text, strlen(text));
    buf_append_gbk(buffer,text, strlen(text));
    buf_append_gbk(buffer,text, strlen(text));
    buf_append_gbk(buffer,text, strlen(text));
    buf_append_gbk(buffer,text, strlen(text));
    char *temp = buf_togbkstring(buffer);
    printf("%s", temp);
    buf_free(buffer);

    return 0;
}

发表评论

邮箱地址不会被公开。 必填项已用*标注