//赋值操作
int strassign(Str & str,char * ch)
{
if(str.ch)
free(str.ch);
int len = 0;
char * c = ch;
while(* c)
{
++len;
++c;
}
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;
int i;
for(i = 0;i <= len;++c)
str.ch[i] = * c;
str.length = len;
return 1;
}
}
}
//取串长度操作
int strlength(Str str)
{
return str.length;
}
//串比较操作
int strcompare(Str s1,Str s2)
{
int i;
for(i = 0;i < s1.length && i < s2.length;++i)
{
if(s1.ch[i] != s2.ch[i])
return s1.ch[i] - s2.ch[i];
}
return s1.length - s2.length;
}
//串的连接操作
int concat(Str & str,Str str1,Str str2)
{
if(str.ch)
{
free(str.ch);
str.ch = null;
}
str.ch = (char *)malloc(sizeof(char) * (str1.length + str2.length + 1));
if(str.ch) = null
return 0;
int i = 0;
while(i < str1.length)
{
str.ch[i] = str1.ch[i];
++i;
}
int j = 0;
while(j < str2.length + 1)
{
str.ch[i + j] = str2.ch[j];
++j;
}
str.length = str1.length + str2.length;
return 1;
}
//求子串操作
int substring(Str & substr,Str str,int pos,int len)
{
if(pos > str.length || pos < 0 || len > str.length - pos || len < 0)
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;
}
substr.ch[j] = '\0';
substr.length = len;
return 1;
}
}
//串清空操作
int clearstring(Str & str)
{
if(str.ch)
{
free(str.ch);
str.ch = null;
}
str.length = 0;
return 1;
}
串的基本操作
最新推荐文章于 2023-01-17 11:31:35 发布