#include <iostream>
#include<stdlib.h>
#define MAX 20
using namespace std;
struct String
{
char* ch;
int length;
};
void InitString(String& s)
{
if (!(s.ch = (char*)malloc((MAX + 1) * sizeof(char))))
return;
s.length = 0;
}
//分配一个大小恰好为所需求的字符串
void StrAssign(String& s, char* t)
{
if (s.ch)
free(s.ch);
int i = 0;
for (char* temp = t; *temp != '\0'; temp++, i++)
;
s.length = i;
if (!(s.ch = (char*)malloc((s.length + 1) * sizeof(char))))
return;
for (i = 0; i < s.length; i++)
s.ch[i] = t[i];
s.ch[i] = '\0';
}
//在s的第pos个位置插入t
void Insert(String& s, int pos, String t)
{
if (pos<1 || pos >= s.length || s.length + t.length>MAX)
return;
for (int i = s.length; i >= pos - 1; i--)//将'\0'也移过去
s.ch[i + t.length] = s.ch[i];
for (int i = 0; i < t.length; i++)
s.ch[i + pos - 1] = t.ch[i];
s.length += t.length;
}
//合并字符串
void Concat(String& s, String t1, String t2)
{
s.length = t1.length + t2.length;
if (!(s.ch = (char*)malloc((s.length + 1) * sizeof(char))))
return;
for (int i = 0; i < t1.length; i++)
s.ch[i] = t1.ch[i];
for (int i = 0; i <= t2.length; i++)
s.ch[i+t1.length] = t2.ch[i];
}
//将sub赋予字符串s中从第pos个位置开始,长度为len的字符串
void SubString(String& sub, String s, int pos, int len)
{
if (pos < 1 || len < 0 || len > s.length - pos+1)
return;
sub.length = len;
if (!(sub.ch = (char*)malloc((sub.length + 1) * sizeof(char))))
return;
for (int i = 0; i < sub.length; i++)
sub.ch[i] = s.ch[i+pos-1];
sub.ch[sub.length] = '\0';
}
int main()
{
String s;
String sub;
InitString(s);
char temp[12] = "Hello world";
StrAssign(s, temp);
SubString(sub, s, 7, 5);
cout << sub.ch;
}