GTK Gossip: GString

GString是GLib所提供的對字串處理的型態,GString保有字串的長度資訊,當您對GString進行插入、附加時,GString會自動調整長度,您也可以搭配一些GLib的函式來方便的處理字串。

GString的定義如下:

typedef struct {
  gchar *str;
  gsize len;   
  gsize allocated_len;
} GString;


str為null結尾的C字串之參考,len為目前字串不包括null結尾的長度,allocated_len為GString所配置的緩衝區長度,如果字串長度超出這個長度會自動重新配置。

您有三種方式可以建立GString:

GString* g_string_new(const gchar *init);
GString* g_string_new_len(const gchar *init, gssize len);
GString* g_string_sized_new(gsize dfl_size);


第一個函式依所給的init字串來建立適當len的GString,並保留適當的allocated_len,建立的時候是將init字元複製至 GString中。第二個函式則是指定len來建立GString,因為是自行指定,所以len必須超過init的長度。第三個函式則是指定 allocated_len來建立GString。

您可以從下面的範例程式看出三個函式的作用:

  • gstring_demo.c
#include <glib.h>

int main(int argc, char *argv[]) {
GString *string = g_string_new("Justin");
g_print("len = %d, allocated_len = %d/n",
string->len, string->allocated_len);
g_string_free(string, FALSE);

string = g_string_new_len("Justin", 32);
g_print("len = %d, allocated_len = %d/n",
string->len, string->allocated_len);
g_string_free(string, FALSE);

string = g_string_sized_new(32);
g_print("len = %d, allocated_len = %d/n",
string->len, string->allocated_len);
g_string_free(string, FALSE);

return 0;
}


若不使用GString時,可以使用g_string_free()釋放,其第二個參數若為TRUE,則會連同C的字串一同釋放。

執行的結果如下所示:

len = 6, allocated_len = 16
len = 32, allocated_len = 64
len = 0, allocated_len = 64


字串的串接可以使用g_string_append()等函式,例如:

GString *string = g_string_new("哈囉!");
g_string_append(string, "GTK 程式設計!");
g_print("%s/n", string->str);


這一段程式碼會在主控台上顯示 "哈囉!GTK 程式設計!"(以UTF8撰寫程式的話可以顯示中文),若想要在前端附加則使用g_string_prepend()等函式,若想要中間插入字元則使用g_string_insert()等函式。

除了單純的附加、插入字元等函式之外,以下還有幾個常用的操作字串的函式:

g_string_equal() 判斷兩個GString的字元內容是否相同
g_string_ascii_up()或g_utf8_strup() 轉換GString中的字元為小寫
g_string_ascii_down()或g_utf8_strdown() 轉換GString中的字元為大寫
g_string_printf() 如printf()一樣的方式,在GString中格式化字串



一個簡單的範例如下所示:

  • gstring_demo.c
#include <glib.h>

int main(int argc, char *argv[]) {
GString *string1, *string2;
gboolean is_eq;

string1 = g_string_sized_new(16);
g_string_printf(string1, "This is %s speaking!", "caterpillar");
g_print("%s/n", string1->str);

string2 = g_string_new("This is caterpillar speaking!");
is_eq = g_string_equal(string1, string2);
g_printf("equal: %s/n", is_eq ? "TRUE" : "FALSE");

g_string_ascii_up(string1);
g_printf("Upper: %s/n", string1->str);
g_string_ascii_down(string1);
g_printf("Down: %s/n", string1->str);

g_string_free(string1, FALSE);
g_string_free(string2, FALSE);

return 0;
}


執行結果如下所示:

This is caterpillar speaking!
equal: TRUE
Upper: THIS IS CATERPILLAR SPEAKING!
Down: this is caterpillar speaking!


除了以上所介紹的,您還可以參考 GString 說明文件 ,另外 GLib 對於字串還提供了 String Utility Functions ,包括更多的字串處理函式。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值