typedef struct Str
{
char *ch;
int length;
}Str;
'''赋值'''
int strAssign(Str& str, char* ch)
{
if(str.ch) //是否指向一片存储空间
free(str.ch);
int len = 0;
char *c = ch;
while(*c)
{
++len; //将要保存的串的长度
++c; //连续存储空间的首地址一直循环到/0
}
if(len == 0) //赋值空串
{
str.ch = NULL;
str.length = 0;
return 1;
}
else
{
str.ch = (char*)malloc(sizeof(char)*(len+1));//申请存储空间
if(str.ch == NULL) //内存满,分配失败
return 0;
else
{ //非空赋值操作
c = ch;
for(int i = 0;i <= len;++i,++c)
str.ch[i] = *c;
str.length = len;
return 1;
}
}
}
'''连接'''
int concat(Str& str,Str s1,Str s2)
{
if(str.ch)//初始化
{
free(str.ch);
str.ch = NULL;
}
str.ch = (char*)malloc(sizeof(char)*(s1.length+s2.length+1));
if(!str.ch)//内存分配失败
return 0;
int i = 0;//赋值s1
while(i < s1.length)
{
str.ch[i] = s1.ch[i];
++i;
}
int j = 0;//赋值s2
while(j < s2.length)
{
str.ch[i+j] = s1.ch[j];
++j;
}
str.length = s1.length+s2.length;
return 1;
}
'''求子串'''
int subString(Str& substr, Str str, int pos, int len)
{
if(pos<0 || pos>=str.length || len<0 || len>str.length-pos)
return 0;
if(substr.ch)
{
free(substr.ch);
substr.ch = NULL;
}
if(len == 0)
{
substr.ch = NULL;
substr.length = 0;
return 1;
}
else
{
substr.ch = (char*)malloc(sizeof(char)*(len+1));
int i = pos;
int j = 0;
while(i<pos+len)
{
substr.ch[j] = str.ch[i];
++i;
++j;
}
}
}
'''取长度'''
int strLength(Str str)
{
return str.length;
}
'''串比较
大于返回正数
小于返回负数
等于返回0'''
int strCompare(Srt s1, Str s2)
{
for(int i = 0 ;i < s1.length && i < s2.length;++i)
if (s1.ch[i] != s2.ch[i])//不是结束符/0
return s1.ch[i] - s2.ch[i];//ASCII差值
return s1.length - s2.length;//是结束符
}
'''清空'''
int strClear(Str& str)
{
if(str.ch)
{
free(str.ch);
str.ch = NULL;
}
str.length = 0;
return 1;
}