堆分配
#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
typedef struct{
char *ch;
int length;
}hstring;
int strassign(hstring &T, char *chars)
{
int i, j;
i = strlen(chars);
if (i == 0)
{
T.ch = NULL;
T.length = 0;
}
else
{
T.ch = (char *)malloc(i*sizeof(char));
for (j = 0; j < i; j++)
T.ch[j] = chars[j];
T.length = i;
}
return OK;
}
int sstrlength(hstring s)
{
return s.length;
}
int strcompare(hstring s, hstring T)
{
int i;
for (i = 0; i < s.length&&i < T.length; ++i)
if (s.ch[i] != T.ch[i])
return s.ch[i] - T.ch[i];
return s.length - T.length;
}
int concat(hstring &T, hstring s1, hstring s2)
{
int i, j;
T.ch = (char *)malloc((s1.length + s2.length)*sizeof(char));
for (i = 0; i < s1.length; i++)
T.ch[i] = s1.ch[i];
for (i = s1.length; i < s1.length + s2.length; i++)
T.ch[i] = s2.ch[i - s1.length];
T.length = s1.length + s2.length;
return OK;
}
int substring(hstring &sub, hstring s, int pos, int len)
{
int i;
if (pos<1 || pos>s.length || len<0 || len>s.length - pos + 1)
return ERROR;
if (len == 0)
{
sub.ch = NULL;
sub.length = 0;
}
else
{
sub.ch = (char *)malloc(len*sizeof(char));
for (i = 0; i < len; i++)
sub.ch[i] = s.ch[i+pos-1];
sub.length = len;
}
for (i = 0; i < len; i++)
cout<<sub.ch[i];
return OK;
}
void shuchu(hstring s)
{
int i;
for (i = 0; i < s.length; i++)
cout << s.ch[i];
}
int main()
{
hstring T, s1, s2, sub;
char *chars1 = "abcde", *chars2 = "jikei";
int m, n;
cout << "将chars1的值赋予s1:";
strassign(s1, chars1);
shuchu(s1);
cout << endl;
cout<<"s1的长度为:"<<sstrlength(s1)<<endl;
cout << "将chars1的值赋予s1:";
strassign(s2, chars2);
shuchu(s2);
cout << endl;
cout << "s2的长度为:"<<sstrlength(s2) << endl;
cout << "判断s1和s2的大小关系:";
if (strcompare(s1, s2)==0)
cout<< "s"<<"1"<<"="<<"s"<<"2" << endl;
else if (strcompare(s1, s2) < 0)
cout << "s" << "1" << "<" << "s" << "2" << endl;
else if (strcompare(s1, s2) > 0)
cout << "s" << "1" << ">" << "s" << "2" << endl;
concat(T, s1, s2);
cout << "将s1与s2连接成新的串T:";
shuchu(T);
cout << endl;
cout << "输入m,n,用来查找串T中第m个字符开始,长度为n的子串sub" << endl;
cin >> m >> n;
cout << "输出子串sub:";
substring(sub, T, m, n);
cout << endl;
system("pause");
return 0;
}