标签:int size malloc 基本 include 分配 creat print erro
#include<stdio.h>
#include<stdlib.h>
//typedef int Status;
#define Max 20
#define OK 1
#define ERROR 0
#define OVERLOE -2
typedef struct//堆分配表示串
{
char *ch;
int length;
}HString;
//===================================================================
int CreatHString(HString &H)//构造字符串
{
H.length = 0;
H.ch = (char *)malloc(Max*sizeof(char));
for (int i = 0; i < Max; i++)
{
H.ch[i]=getchar();
H.length++;
if (getchar() == ‘\n‘)
break;
}
return OK;
}//CreatHString
//===================================================================
int PrintHString(HString H)//输出所输入的字符串
{
if (H.length == 0)
{
printf( "空串!" );
return ERROR;
}
else
for (int i = 0; i < H.length; i++)
printf("%c",H.ch[i]);
printf("\n");
return OK;
}//PrintHString
//===================================================================
int HStringLength(HString H)//求字符串的长度
{
printf( "您输入的字符串长度为:" );
printf(" %d ",H.length);
return OK;
}//HStringLength
//===================================================================
int HStringCompare(HString H, HString T)//求两个字符串长度差(绝对值)
{
printf( "两个字符串的长度差为:" );
int L;
L = H.length - T.length;
if (L<0)
printf("%d",-L);
if (L>=0)
printf("%d",L);
return OK;
}//HStringCompare
//===================================================================
int ConcatHString(HString &S, HString H, HString T)//链接H和T
{
if (!(S.ch = (char *)malloc((H.length + T.length)*sizeof(char))))
exit(OVERLOE);
for (int i = 0; i < H.length; i++)
S.ch[i] = H.ch[i];
S.length = H.length + T.length;
for (int j = H.length; j < S.length; j++)
S.ch[j] = T.ch[j-H.length];
return OK;
}//ConcatHString
//===================================================================
int SubHString(HString &Sub, HString S, int pos,int len)
{//用Sub返回串S的第pos个字符起长度为len的子串
if (pos<1 || pos>S.length)
{
printf( "输入的位置有误!" );
return ERROR;
}
if (len<0 || len>S.length - pos + 1)
{
printf( "输入的长度有误!" );
return ERROR;
}
if (!len)
{
Sub.ch = NULL;
Sub.length = 0;
}
else
{
Sub.ch = (char *)malloc(len*sizeof(char));
for (int i = 0; i < len ; i++)
Sub.ch[i] = S.ch[pos + i - 1];
Sub.length = len;
}
return OK;
}//SubHString
//===================================================================
int ClearHString(HString &H)//将H清为空串
{
if (H.ch)
{
free(H.ch);
H.ch = NULL;
}
H.length = 0;
return OK;
}//ClearHString
//===================================================================
void main()
{
HString S,H,T;
printf( "请输入一个字符串(按回车键结束):" );
CreatHString(H);
printf("现在串中的字符为:" );
PrintHString(H);
HStringLength(H);
printf( "请再输入一个字符串(按回车键结束):" );
CreatHString(T);
HStringCompare(H, T);
ConcatHString(S, H, T);
printf("现在串中的字符为:" );
PrintHString(S);
HString Sub;
int pos, len;
printf( "请输入截取位置pos及长度len:" );
scanf( "%d%d",&pos,&len);
SubHString(Sub, S, pos, len);
printf( "截取的子串为:" );
PrintHString(Sub);
ClearHString(S);
printf ("检验S清空后是否为空:" );
PrintHString(S);
}//main
标签:int size malloc 基本 include 分配 creat print erro
原文地址:http://www.cnblogs.com/youdiaodaxue16/p/7857766.html