C語言實現串的堆分配儲存

2021-06-16 07:04:23 字數 1943 閱讀 3347

/*

* heap_string.h

* 串的堆分配儲存實現,用這種實現方法的好處是,能夠動態的給

* 串分配記憶體空間,而順序串不能

* created on: 2011-9-7

* author: root

*/#define elemtype char;

#define true 1

#define false 0

typedef struct hstring;

//初始化串

void inithstring(hstring *s)

//用字串常量建立串

int createhstring(hstring *s,char chars)

if(i == 0) return false;

s->length = i;

s->ch = (char *)malloc(sizeof(char) * s->length);

if(s->ch == null) return false;

for(i = 0;i < s->length;i ++)

s->ch[i ++] = '\0';

return true;

}//比較兩個串是否相等若s1>s2返回值》0若s10) return s1.ch[i] - s2.ch[i];

i ++;

} return s1.length - s2.length;

}//取得串長度,串中字元的個數稱為串的長度

int hstringlength(hstring s)

//清空字串並釋放串的所有空間

void hstringclear(hstring *s)

}//將s1和s2鏈結為乙個串

int hstringconnection(hstring *s,hstring s1,hstring s2)

for(;i < s->length;i ++)

s->ch[i] = '\n';

return true;

}//從串中擷取一段串擷取規則是從first開始,從end前乙個結束

int hstringsub(hstring *s,hstring hs,int first,int end)

s->ch[s->length] = '\n';

return true;}/*

* 串匹配得到子串t在串s中pos個字元後的開始位置

* 0< pos <= s->length

* 若pos後存在字串返回其位置 否則返回0

*/int hstringindex(hstring s,hstring t,int pos) else

if(j == t.length) return i - j + 1;

} return 0;

}//輸出串

void printfhstring(hstring *s)

puts(s->ch);

printf("length = %d\n",s->length);}/*

* hstring.c

* 測試heap_string.h

* created on: 2011-9-7

* author: root

*/#include #include #include "heap_string.h"

int main(void)

//控制台結果

liu sheng

length = 9

liu_sheng

length = 9

compare = 0

liu shengliu_sheng

length = 18

liu sheng

length = 9

shen

length = 4

5

C語言實現資料結構串(堆分配儲存表示法)例項詳解

堆分配儲存表示法 儲存結構 構建堆來儲存字串,本質上是順序表 實現 include include include define ok 1 define error 0 define true 1 define false 0 define overflow 2 define str init si...

堆儲存串的實現(c語言)

1.str.h ifndef str h define str h typedef struct str str newstr char str void destroystr str s void clearstr str s int strcompare str s,str t int strc...

串的堆分配儲存表示

串的堆分配儲存表示 方法仍然以一組位址連續的儲存單元表示,但它們的儲存 空間是在程式執行過程中動態分配的。堆串型別定義 typedef strcut hstring hstring 堆串常用基本操作的演算法描述 串賦值int strassign hstring s,char chars else s...