include
typedef struct HString{
char data;
struct HString *next;
} HString;
void Print(HString T)
{
HString *p;
p = &T;
while(p->next != NULL)
{
p=p->next;
printf("%c", p->data);
}
printf("\n");
}
void StrAssign(HString *T, char chars[], int n)
{
HString *p, *q;
p = T;
int i;
for(i = 0; i < n; i++)
{
q = (HString*)malloc(sizeof(HString));
q->data = chars[i];
q->next = NULL;
p->next = q;
p = q;
}
Print(*T);
}
int StrLen(HString *T)
{
HString *p;
p = T;
int i = 0;
while(p->next != NULL)
{
i++;
p = p->next;
}
return i;
}
int StrCompare(HString *T, HString *S)
{
HString *pt, *ps;
pt = T->next;
ps = S->next;
while(pt != NULL && ps != NULL)
{
if(pt->data == ps->data)
{
pt = pt->next;
ps = ps->next;
}
else if(pt->data > ps->data)
{
return 1;
}
else
{
return -1;
}
}
if(StrLen(S) == StrLen(T)) return 0;
else if (StrLen(S) < StrLen(T))
{
return 1;
}
else
{
return -1;
}
}
HString StrConcat(HString *T, HString *Ta, HString *Tb)
{
HString *pa, *pb;
pa = T = Ta;
pb = Tb;
while(pa->next != NULL)
{
pa = pa->next;
}
pa->next = pb->next;
Print(*T);
return *T;
}
int SubString(HString *Sub, HString *S, int pos, int len)
{
int i = 0, j = 0;
HString *p, *ps, *q;
p = S;
ps = Sub;
if(0 < pos && pos <= StrLen(S) && 0 < len && len <= StrLen(S)-pos+1)
{
while(i < pos)
{
p = p->next;
i++;
}
while(j < len)
{
q = (HString*)malloc(sizeof(HString));
q->data = p->data;
q->next = NULL;
ps->next = q;
ps = q;
p = p->next;
j++;
}
Print(*Sub);
return pos;
}
return -1;
}
int main()
{
HString T, S, S1, Sub, C2, C3;
char chars[4] = "chas";
printf("StrAssign: ");
StrAssign(&T, chars, 4);
char c1[5];
int i;
printf("请输入5个字符: ");
for(i = 0; i < 5; i++)
{
scanf("%c", &c1[i]);
}
StrAssign(&S, c1, 5);
printf("字符串连接后:");
S1 = StrConcat(&S1, &T, &S);
printf("连接后字符串长度:%d\n", StrLen(&S1));
int pos, len;
printf("请输入要截取字符串的起始位置和长度:");
scanf("%d %d", &pos, &len);
printf("子串长度:");
SubString(&Sub, &S1, pos, len);
int n;
printf("请输入字符个数及字符: ");
scanf("%d", &n);
char c2[n];
for(i = 0; i < n; i++)
{
scanf("%c", &c2[i]);
}
StrAssign(&C2, c2, n);
printf("请输入字符个数及字符: ");
scanf("%d", &n);
char c3[n];
for(i = 0; i < n; i++)
{
scanf("%c", &c3[i]);
}
StrAssign(&C3, c3, n);
printf("字符串比较结果:%d", StrCompare(&C2, &C3));
return 0;
}