顺序串为静态顺序存储表示,在串的插入,连接过程中如果长度超过了MaxSize就会截掉一部分。
因此可以使用动态分配存储表示串
头文件
#pragma once
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
typedef struct
{
char *str;
int length;
} HeapString;
void InitSring(HeapString *S)
/*初始化*/
{
S->length = 0;
S->str = '\0';
}
void StrAssign(HeapString *S, char cstr[])
/*赋值*/
{
int i = 0;
int len = strlen(cstr); // 获取字符串长度
if (len == 0)
{
S->length = 0;
S->str = '\0';
}
else
{
S->str = (char *)malloc(sizeof(char)*len); // 为字符串分配空间
if (!S->str)
exit(-1);
else // 开始赋值操作
{
for (i = 0; i < len; i++)
S->str[i] = cstr[i];
S->length = len;
}
}
}
void StrCopy(HeapString *T, HeapString S)
/*复制串*/
{
int i;
T->str = (char*)malloc(S.length * sizeof(char));
if (!T->str)
exit(-1);
else
{
for (i = 0; i < S.length; i++)
{
T->str[i] = S.str[i];
}
T->length = S.length;
}
}
int StrInsert(HeapString *T,int pos, HeapString S)
/*在第pos个的位置拆入一个字符串,成功返回1*/
{
int i;
if (pos<0 || pos > T->length)
{
std::cout << "插入位置不正确\0";
return 0;
}
else
{
T->str = (char *)realloc(T->str, (S.length + T->length) * sizeof(char));//再分配一块地址,直到两个字符造串的长度
if (!T->str)
{
std::cout << "内存分配失败\0";
exit(-1);
}
for (i = pos - 1; i < T->length; i++)//复制后半段
{
T->str[i + S.length] = T->str[i];
}
for (i = pos - 1; i < pos + S.length; i++) // 赋值
T->str[i] = S.str[i - pos + 1];
T->length += S.length;
return 1;
}
}
int DeleteStr(HeapString *S, int pos, int len)
/*删除pos开始的len个字符,pos为位置*/
{
int i;
char *p;
if (pos<0 || len + pos - 1 > S->length)
{
std::cout << "删除位置不对,参数len不合法\n";
return 0;
}
p = (char*)malloc((S->length - len) * sizeof(char));
if (!p)
exit(-1);
for (i = 0; i < pos - 1; i++) //将pos前面的赋值到p中
{
p[i] = S->str[i];
}
for (i = pos - 1 + len; i < S->length; i++)//将pos后面的赋值到p中
{
p[i-len] = S->str[i];
}
S->length -= len;
free(S->str);//释放空间
S->str = p;
return 1;
}
int StrCat(HeapString *T, HeapString S)
/*将S连接在T的后面,成功返回1*/
{
int i;
T->str = (char*)realloc(T->str, (T->length + S.length) * sizeof(char));
if (!T->str)
exit(-1);
for (i = T->length; i < (T->length + S.length); i++)
{
T->str[i] = S.str[i - T->length];
}
T->length += S.length;
return 1;
}
void StrDestroy(HeapString *S)
//销毁串
{
free(S->str);
S->str = '\0';
S->length = 0;
}