串的堆分配储存表示
typedef struct {
char* ch;//若是非空字符串,则按串长分配存储区,否则ch为NULL
int length;//串长度
} HString;
生成一个其值等于串常量的串
HString StrAssign(HString Str, char* chars) {
//生成一个其值等于串常量的chars的串T
if (Str.ch) {
//释放T的空间
free(Str.ch);
}
int len = 0;
printf_s("chars=%s\n", chars);
while (1) {
len++;
if (chars[len] == '\0') {
//TODO
break;
}
}
if (!len) {
//长度为0为ch赋NULL值
Str.ch = NULL;
Str.length = 0;
}
else {
if (!(Str.ch = (char*)malloc(len * sizeof(char)))) {
//空间不足退出
exit(ERROR);
}
for (int i = 0; i <= len - 1; i++) {
//TODO
Str.ch[i] = chars[i];
}
Str.ch[len] = '\0';
printf("Str.ch=%s\n", Str.ch);
Str.length = len;
}
return Str;
}
比较字符串
int StrCompares(HString S, HString T) {
// 若S>T,则返回值>0;若S<T,则返回值=0,若S<T,则返回值<0
printf_s("123\n");
for (int i = 0; i <= S.length && i < T.length; ++i) {
//TODO
if (S.ch[i] != T.ch[i]) {
//TODO
return S.ch[i] - T.ch[i];
}
}
return S.length - T.length;
}
清空串
HString ClearString(HString S) {
// 将S清为空串
if (S.ch) {
//TODO
free(S.ch);
S.ch = NULL;
}
S.length = 0;
return S;
}
链接新串
HString Concat(HString T, HString S1, HString S2) {
//用T返回由S1和S2链接而成的新串
if (T.ch)
{
free(T.ch);//释放旧空间
}
if (!(T.ch = (char*)malloc((S1.length + S2.length) * sizeof(char))))
{
exit(ERROR);
}
for (int i = 0; i < S1.length; i++)
{
printf("i=%d\n", i);
T.ch[i] = S1.ch[i];
}
T.length = S1.length + S2.length;
for (int i = S1.length; i < T.length; i++)
{
T.ch[i] = S2.ch[i - S1.length];
}
T.ch[T.length] = '\0';
return T;
}
用Sub返回串S的第pos个字符起长度为len的子串
HString SubString(HString Sub, HString S, int pos, int len) {
//用Sub返回串S的第pos个字符起长度为len的子串
//其中,1<=pos<=StrLength(S)&&0<=len<=StrLength(S)-pos+1
if (pos<1 || pos>S.length || len<0 || len>S.length - pos + 1)
{
exit(ERROR);
}
if (Sub.ch)
{
//释放旧空间
free(Sub.ch);
}
if (!len)
{
//空子串
Sub.ch = NULL;
Sub.length = 0;
}
else
{
Sub.ch = (char*)malloc(len * sizeof(char));
int lengthNum = 0;
int posNum = 1;
while (1)
{
Sub.ch[lengthNum] = S.ch[posNum];
lengthNum++;
posNum++;
if (posNum == pos + len && posNum <= S.length)
{
break;
}
}
Sub.length = len;
Sub.ch[len] = '\0';
}
return Sub;
}
标签:ch,Sub,int,HString,len,C语言,length,操作,数据结构
From: https://www.cnblogs.com/homeskating/p/17152614.html