串
1.定长的串
#define MAXSIZE = 10
struct String
{
char str=[MAXSIZE];//储存串字符的数组
int len;//串字符的长度
};
2.变长的串
struct String
{
char* pstr;//开辟内存
int totalsize;//串当前最大长度
int cursize;//串当前有效长度
};
创建文件“main.cpp”
#include<stdio.h>
#include"String.h"
int main()
{
String str;
initString(&str);
strAssign(&str,"hello");
strPrint(&str);
String str2;
initString(&str2);
strAssign(&str2,"hi ");
String str3;
initString(&str3);
strAssign(&str3,"world");
strSub(&str,&str2,&str3);
strPrint(&str);
}
创建文件“string.h”
#include<stdlib.h>
#include<stdio.h>
typedef struct String
{
char* pstr;
int total;//总大小
int cur;//有效元素大小
}String,*PString;
void initString(PString ps);
void strAssign(PString ps,char* p);
void strSub(PString ps,PString p1,PString p2);
void strPrint(PString ps);
void destroyed(PString ps);
创建文件“string,cpp”
#include<stdio.h>
#include<string,h>
#include<stdlib.h>
#include"String.h"
void initString(PString ps)
{
if(ps != NULL)
{
ps->pstr = NULL;
ps->total = ps->cur = 0;
}
}
void strAssign(PString ps,char* p)
{
int i = 0;
int len = strlen(p);//字符串有效长度
if(ps->pstr != NULL)//ptr ! NULL 串非空 释放旧空间
{
free(ps->pstr);
}
if(len == 0)
{
ps->pstr = NULL;
ps->total = ps->cur = 0;
}
else//字符串非空
{
ps->pstr = (char*)malloc(sizeof(char)*len);
for(i = 0;i < len;i++)
{
ps->pstr[i] = p[i];
}
ps->total = len;
ps->cur = len;
}
}
void strSub(PString ps,PString p1,PString p2)
{
int len1 = p1->cur;
int len2 = p2->cur;
int i = 0;
int j = 0;
if(ps->pstr != NULL)
{
free(ps->pstr);
}
if(!len1 && !len2)
{
ps->pstr = NULL;
ps->total = ps->cur = 0;
}
else
{
ps->pstr = (char*)malloc(sizeof(char)*(len1 + len2));
for(j = 0;j < len1; j++)
{
ps->pstr[i++] = p1->pstr[j];
}
for(j = 0;j <len2;j++)
{
ps->pstr[i++] = p2->pstr[j];
}
ps->total = (len1 + len2);
ps->cur = (len1 + len2);
}
}
void destroyed(PString ps)
{
if(ps != NULL)
{
free(ps->pstr);
}
ps->total = ps->cur = 0;
}
void strPrint(PString ps)
{
int i = 0;
for(i;i < ps->cur;i++)
{
printf("%c",ps->pstr[i]);
}
printf("\n");
}