用C语言写一个串的堆分配存储结构
时间: 2024-06-13 10:06:37 浏览: 81
下面是一个用C语言实现的串的堆分配存储结构的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct HString {
char *ch; //指向字符串所在空间首地址
int length; //记录字符串长度
} HString;
//初始化一个空串
void InitString(HString *s) {
s->ch = (char *)malloc(sizeof(char));
s->length = 0;
}
//销毁串
void DestroyString(HString *s) {
free(s->ch);
s->ch = NULL;
s->length = 0;
}
//清空串
void ClearString(HString *s) {
s->ch[0] = '\0';
s->length = 0;
}
//判断串是否为空
int StringEmpty(HString *s) {
return s->length == 0;
}
//获取串的长度
int StringLength(HString *s) {
return s->length;
}
//复制串
void StringCopy(HString *s, HString *t) {
if (s->ch) {
free(s->ch);
s->ch = NULL;
}
s->ch = (char *)malloc(sizeof(char) * (t->length + 1));
strcpy(s->ch, t->ch);
s->length = t->length;
}
//比较串
int StringCompare(HString *s, HString *t) {
int i = 0;
while (i < s->length && i < t->length) {
if (s->ch[i] != t->ch[i]) {
return s->ch[i] - t->ch[i];
}
i++;
}
return s->length - t->length;
}
//连接串
void StringConcat(HString *s, HString *t) {
int len = s->length + t->length;
char *new_ch = (char *)malloc(sizeof(char) * (len + 1));
strcpy(new_ch, s->ch);
strcat(new_ch, t->ch);
free(s->ch);
s->ch = new_ch;
s->length = len;
}
//获取子串
void SubString(HString *sub, HString *s, int pos, int len) {
if (pos < 1 || pos > s->length || len < 0 || pos + len - 1 > s->length) {
printf("Error: invalid position or length.\n");
return;
}
if (sub->ch) {
free(sub->ch);
sub->ch = NULL;
}
sub->ch = (char *)malloc(sizeof(char) * (len + 1));
strncpy(sub->ch, s->ch + pos - 1, len);
sub->ch[len] = '\0';
sub->length = len;
}
//在串中查找子串
int Index(HString *s, HString *t, int pos) {
int i = pos;
int j = 1;
while (i <= s->length && j <= t->length) {
if (s->ch[i - 1] == t->ch[j - 1]) {
i++;
j++;
} else {
i = i - j + 2;
j = 1;
}
}
if (j > t->length) {
return i - t->length;
} else {
return 0;
}
}
//输出串
void PrintString(HString *s) {
printf("%s\n", s->ch);
}
int main() {
HString s, t, sub;
InitString(&s);
InitString(&t);
InitString(&sub);
//初始化串
s.ch = "hello";
s.length = strlen(s.ch);
t.ch = "world";
t.length = strlen(t.ch);
//测试各个操作
StringCopy(&sub, &s);
StringConcat(&sub, &t);
PrintString(&sub);
SubString(&sub, &s, 2, 3);
PrintString(&sub);
printf("%d\n", Index(&s, &t, 1));
//销毁串
DestroyString(&s);
DestroyString(&t);
DestroyString(&sub);
return 0;
}
```
阅读全文