alimyso 发表于 2010-8-30 17:30:17

GString基本操作二

该演示主要操作一个字符串,分解成单个字符,同时获取字符串长度,部分字符串等
作者:AlimysoYang


#include <gtk/gtk.h>

GtkWidget *wnd;
GtkWidget *vbox,*hbox;
GtkWidget *entry,*btntest,*btnquit;

void ui_init()
{
    wnd = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_window_set_title(GTK_WINDOW(wnd),"Test GString");
    gtk_window_set_position(GTK_WINDOW(wnd),GTK_WIN_POS_CENTER);
   
    vbox = gtk_vbox_new(TRUE,2);
    hbox = gtk_hbox_new(TRUE,2);
    entry = gtk_entry_new();
    btntest = gtk_button_new_with_label("测试");
    btnquit = gtk_button_new_with_label("退出");
    gtk_box_pack_start_defaults(GTK_BOX(hbox),btntest);
    gtk_box_pack_start_defaults(GTK_BOX(hbox),btnquit);
   
    gtk_box_pack_start_defaults(GTK_BOX(vbox),entry);
    gtk_box_pack_start_defaults(GTK_BOX(vbox),hbox);
   
    gtk_container_add(GTK_CONTAINER(wnd),vbox);
    gtk_container_set_border_width(GTK_CONTAINER(wnd),5);
    gtk_widget_show_all(wnd);
}

void FormDestroy(GtkWidget *widget,GdkEvent *event,gpointer data)
{
    gtk_main_quit();
}

void btntest_clicked(GtkButton *button,gpointer data)
{
    GString *teststr;
    const gchar *textc = gtk_entry_get_text(GTK_ENTRY(entry));
    teststr = g_string_new(textc);

    int len = teststr->len;
    g_printf("GString Len:%d\n",len);
    g_printf("GString Allocated_Len:%d\n",teststr->allocated_len);
    g_printf("GString Value:%s\n",teststr->str);
    int i;
    for (i = 0;i<len;i++)
    g_printf("GString Value[%d]:%c\n",i,teststr->str);
   
    GString *partstr = g_string_sized_new(len - 2);
    for (i = 1;i<=len - 2;i++)
    g_string_append_c(partstr,teststr->str);
    g_printf("PartStr GString Len And PartStr:%d %s\n",partstr->len,partstr->str);
    g_string_free(teststr,TRUE);
}

int main(int argc,char *argv[])
{
    gtk_init(&argc,&argv);
   
    ui_init();
   
    g_signal_connect(G_OBJECT(wnd),"destroy",G_CALLBACK(FormDestroy),NULL);
    g_signal_connect_swapped(G_OBJECT(btnquit),"clicked",G_CALLBACK(FormDestroy),NULL);
    g_signal_connect(G_OBJECT(btntest),"clicked",G_CALLBACK(btntest_clicked),NULL);
    gtk_main();
    return 0;
}

Tom 发表于 2010-8-30 20:09:47

嗯,不错,呵呵,发贴,贴代码的时候,编辑框上有个代码的标签,这样效果会比较好一点。

gtk-inkscape 发表于 2010-10-30 07:06:19

嗯~~收藏啦。谢谢LZ。

ekd123 发表于 2011-9-11 00:26:45

个人觉得 GString 里面 g_string_printf 最好用!很方便,而且不会溢出!
页: [1]
查看完整版本: GString基本操作二