C Programer  - 讨论区

标题:GLib库GString模块编程示例

2014年02月02日 星期日 16:07

GString是一种动态字符串数据结构,提供了丰富灵活方便的API,无需手工分配内存,无需担心缓冲区溢出。编程示例如下:

#include <stdio.h>
#include <glib.h>

int main(int argc,char **argv) {

    GString *s=g_string_new("Hello World.");
    printf("From GString: %s\n",s->str);
    printf("Length: %d\n",s->len);
    printf("Capaticy: %d\n",s->allocated_len);
    
    GString *t=g_string_new("Hello Laomeng.");
    if(g_string_equal(s,t)) {
        printf("%s  == %s\n",s->str,t->str);
    } else {
        printf("%s != %s\n",s->str,t->str);
    }
    
    g_string_ascii_up(s);
    printf("From GString: %s\n",s->str);
    g_string_ascii_down(s);
    printf("From GString: %s\n",s->str);

    g_string_append(s,"Hello Universe.");
    printf("From GString: %s\n",s->str);
    printf("Length: %d\n",s->len);
    printf("Capaticy: %d\n",s->allocated_len);

    g_string_truncate(s,0);
    printf("From GString: %s\n",s->str);
    printf("Length: %d\n",s->len);
    printf("Capaticy: %d\n",s->allocated_len);

    g_string_printf(s,"%d + %d = %d",
            100,200,100+200);
    printf("From GString: %s\n",s->str);
    printf("Length: %d\n",s->len);
    printf("Capaticy: %d\n",s->allocated_len);

    g_string_append_printf(s,"\t %d * %d = %d",
            100,200,100*200);
    printf("From GString: %s\n",s->str);
    printf("Length: %d\n",s->len);
    printf("Capaticy: %d\n",s->allocated_len);

    g_string_free(s,TRUE);
    g_string_free(t,TRUE);
    
    return 0;
}

参考资料:

https://developer.gnome.org/glib/2.39/glib-Strings.html

 

如下红色区域有误,请重新填写。

    你的回复:

    请 登录 后回复。还没有在Zeuux哲思注册吗?现在 注册 !

    Zeuux © 2024

    京ICP备05028076号