串的堆分配存储结构代码
时间: 2023-11-30 21:41:08 浏览: 114
以下是串的堆分配存储结构的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct HString {
char *ch; //指向字符串所在空间首地址
int length; //记录字符串长度
} HString;
// 初始化一个空串
void InitString(HString *s) {
s->ch = NULL;
s->length = 0;
}
// 生成一个值等于chars的串T
void StrAssign(HString *T, char *chars) {
int i = 0;
char *c = chars;
while (*c) {
++i;
++c;
}
if (!i) {
T->ch = NULL;
T->length = 0;
} else {
T->ch = (char *) malloc(i * sizeof(char));
if (!T->ch) {
exit(-1);
}
c = chars;
for (int j = 0; j < i; ++j) {
T->ch[j] = *c;
++c;
}
T->length = i;
}
}
// 由串S复制得串T
void StrCopy(HString *T, HString *S) {
if (T->ch) {
free(T->ch);
T->ch = NULL;
}
T->ch = (char *) malloc(S->length * sizeof(char));
if (!T->ch) {
exit(-1);
}
for (int i = 0; i < S->length; ++i) {
T->ch[i] = S->ch[i];
}
T->length = S->length;
}
// 若S为空串,则返回true,否则返回false
int StrEmpty(HString *S) {
return S->length == 0;
}
// 若S>T,则返回值>0;若S=T,则返回0;若S<T,则返回值<0
int StrCompare(HString *S, HString *T) {
for (int i = 0; i < S->length && i < T->length; ++i) {
if (S->ch[i] != T->ch[i]) {
return S->ch[i] - T->ch[i];
}
}
return S->length - T->length;
}
// 返回串的长度
int StrLength(HString *S) {
return S->length;
}
// 将S清空为空串
void ClearString(HString *S) {
if (S->ch) {
free(S->ch);
S->ch = NULL;
}
S->length = 0;
}
// 用T返回由S1和S2联接而成的新串
void Concat(HString *T, HString *S1, HString *S2) {
if (T->ch) {
free(T->ch);
T->ch = NULL;
}
T->ch = (char *) malloc((S1->length + S2->length) * sizeof(char));
if (!T->ch) {
exit(-1);
}
for (int i = 0; i < S1->length; ++i) {
T->ch[i] = S1->ch[i];
}
for (int i = 0; i < S2->length; ++i) {
T->ch[S1->length + i] = S2->ch[i];
}
T->length = S1->length + S2->length;
}
// 用Sub返回串S的第pos个字符起长度为len的子串
void SubString(HString *Sub, HString *S, int pos, int len) {
if (pos < 1 || pos > S->length || len < 0 || pos + len - 1 > S->length) {
exit(-1);
}
if (Sub->ch) {
free(Sub->ch);
Sub->ch = NULL;
}
if (!len) {
Sub->ch = NULL;
Sub->length = 0;
} else {
Sub->ch = (char *) malloc(len * sizeof(char));
if (!Sub->ch) {
exit(-1);
}
for (int i = 0; i < len; ++i) {
Sub->ch[i] = S->ch[pos + i - 1];
}
Sub->length = len;
}
}
// 在串S的第pos个字符前插入串T
void StrInsert(HString *S, int pos, HString *T) {
if (pos < 1 || pos > S->length + 1) {
exit(-1);
}
if (T->length) {
S->ch = (char *) realloc(S->ch, (S->length + T->length) * sizeof(char));
if (!S->ch) {
exit(-1);
}
for (int i = S->length - 1; i >= pos - 1; --i) {
S->ch[i + T->length] = S->ch[i];
}
for (int i = 0; i < T->length; ++i) {
S->ch[pos + i - 1] = T->ch[i];
}
S->length += T->length;
}
}
// 从串S中删除第pos个字符起长度为len的子串
void StrDelete(HString *S, int pos, int len) {
if (pos < 1 || pos > S->length || len < 0 || pos + len - 1 > S->length) {
exit(-1);
}
for (int i = pos - 1; i < S->length - len; ++i) {
S->ch[i] = S->ch[i + len];
}
S->length -= len;
S->ch = (char *) realloc(S->ch, S->length * sizeof(char));
if (!S->ch && S->length) {
exit(-1);
}
}
```
阅读全文