一、串与字符串的比较
1、串:一系列有限字符的集合
2、字符串:编程语言种表示文本的数据类型。它也是一系列有限字符的集合。
但从概念上发现两者没有多大的区别。但我们往往在处理串的时候,是有它的特殊结构,处理字符串的时候是打包在一起,用cha*来处理。
二、串的分类
串分为一般分为定长顺序串和变长串
1、定长顺序串
#define MAXSIZE 10
struct String
{
char str[MAXSIZE];//存储串字符的数组
int len;//当前串的长度
};
2、变长串
struct String
{
char* pstr;//开辟内存
int totalsize;//串当前最大的长度
int cursize;//串当前的有效长度
};
三、变长串的实现
1、结构
String str;//定义的一个串
它的结构如下所示:
整体结构定义如下:
struct String
{
char* pstr;//开辟内存
int totalsize;//串当前最大的长度
int cursize;//串当前的有效长度
}String,*PString;
2、初始化(initString)
void initString(PString ps)
{
if(ps != NULL)
{
ps->pstr = NULL;
ps->total = ps->cur= 0;
}
}
3、赋值(strAssign)
(1)字符串为空
(2)字符串不为空
当串中已有字符"hello"时,我们插入“hello world”时,要先将原来内存所指向的字符串释放掉,再重新开辟新的内存,最后将新的数据赋值。,然后将total和cur重新修改。如上图所示
void strAssign(PString ps, char* p)
{
int i = 0;
int len = strlen(p);//字符串的有效长度
if(ps->ptr != NULL);//ptr != NULL 串非空 释放就空间
{
free(ps->ptr);
}
if(!len)//字符串是NULL
{
ps->ptr == NULL;
ps->total = ps->cur = 0;
}
else//字符串非空
{
ps->ptr = (char*)malloc(sizeof(char)*len);
for(i = 0; i < len; i++)
{
ps->ptr[i] = p[i];
}
ps->total = len;
ps->cur = len;
}
}
4、合并两个字符串
void strSub(PString ps, PString p1, PString p2)
{
int len1 = p1->cur;
int len2 = p2->cur;
int i = 0;
int j = 0;
if(ps->ptr != NULL)
{
free(ps->ptr);
}
if(!len1 && !len2)//len1==0&&len2==0 (p1,p2)为空串
{
ps->ptr = NULL;
ps->total = ps->cur = 0;
}
else
{
ps->ptr = (char*)malloc(sizeof(char)*(len1+len1));
for(j = 0; j < len1; j++)
{
ps->ptr[i++] = p1->ptr[j];
}
for(j = 0; j < len2;j++)
{
ps->ptr[i++] = p2->ptr[j];
}
ps->total = (len1 + len2);
ps->cur = (len +len2);
}
}
5、销毁
void destrioyed(PString ps)
{
if(ps != NULL)//串是否存在
{
free(ps->ptr);
}
ps->total = ps->cur = 0;
}
5、打印函数
void strPrint(PString ps)
{
int i = 0;
for(i; i<ps->cur;i++)
{
printf("%c",ps->ptr[i]);
}
printf("\n");
}