欢迎大家访问我的个人博客:endeavorchuan.com
动态分配存储表示
在程序执行过程中可动态分配存储空间
typedef struct //定义结构体
{
char *ch; //此字符指针指向动态分配存储区的首地址
int length; //length指串的长度
}Str;
使用malloc函数动态分配内存,若分配成功,使用ch指向起始地址,用做的基地址。
串的赋值
串是一个数组,所以赋值不能使用“=”,必须对数组中的每个元素进行逐一赋值操作。
int strassign( Str& str, char* ch )
{
if( str.ch ) //若串不为空
free( str.ch ); //释放原串的空间
int len = 0; //定义串的初始 长度为0
char *c = ch; //定义指针c
while( *c ) //求串ch的长度,当c不为空时,一直递加
{
++len; //长度递加
++c; //指针向后移一位
}
if( len == 0 ) //若串的长度为0,则直接返回空串
{
str.ch = NULL; //串为NULL
str.length = 0; //串的长度为0
return 1;
}
else
{
str.ch = ( char* ) malloc ( sizeof ( char ) * ( len+1 ) );
//动态分配存储空间,串长为len,分配len+1是为了存放'\0',用于结束标志
if( str.ch == NULL ) //若存储空间分配失败
return 0; //返回分配失败信号
else //存储空间分配成功
{
c = ch;
for( int i=0; i<=len; ++i,++c ) //循环len次,为串赋值
str.ch[i] = *c;
str.length = len; //更新串的长度为len
return 1;
}
}
}
求串长度
int strlength( Str str )
{
return str.length; //返回值为串的长度
}
串的比较操作
以 i 为计数器,在未比较出两串大小的情况下,先结束的串为小串,两串同时结束,则两串长度相等。
int strcompare( Str s1, Str s2 ) //比较串s1与s2的大小
{
for( int i=0; i<s1.length && i<s2.length; ++i ) //若i计数并未溢出
if( s1.ch[i] != s2.ch[i] ) //若s1与s2的第i个元素值不等
return s1.ch[i] - s2.ch[i];
return s1.length - s2.length; //返回两串相差长度的大小
}
串连接操作
将两个串首尾连接,形成一个新的字符串。
int concat( Str& str, Str str1, Str str2 )
//str表示最后由str1和str2连接的总串,因为值需要改变,所以使用&表示引用型
{
if( str.ch ) //若原串非空
{
free( str.ch ); //释放原串占有空间
str.ch = NULL; //将串str置空
}
str.ch = ( char* )malloc( sizeof ( char ) * ( str1.length + str2.length + 1 ));
//为串str动态分配内存,内存长度为str1+str2+1,多余的1位‘\0’,用于串结束标志
if( str.ch == NULL ) //若内存分配失败
return 0; //返回分配失败信号
int i=0; //定义i为str1的计数器
while( i<str1.length ) //当i的值小于str1.length时
{
str.ch[i] = str1.ch[i]; //将str1中的元素依次存入str中
++i; //计数器加一
}
int j=0; //定义j为str2的计数器
while( j<=str2.length ) //当j的值小于str2.length时
{
str.ch[i+j] = str2.ch[j]; //将str2的元素,依次加入到str中,排在str1之后
++j; //计数器加一
}
str.length = str1.length + str2.length; //str的长度为str1与str2长度之和
return 1; //串连接成功
}
求子串操作
在一给定的主串中,求从给定起始位置到截止位置的串的操作。
求str串中,从pos位置开始,长度为len的子串,子串由substr返回。
int substring( Str& substr, Str str, int pos, int len )
//str为主串,pos指子串开始位置,len为子串长度,substr为子串,因为值需要改变,用&表示引用型
{
if( pos<0 || pos>=str.length || len<0 || len>str.length-pos )
//若输入的pos值与len值不合法
return 0; //程序结束,返回不合法信号
if( substr.ch ) //若substr非空
{
free( substr.ch ); //释放substr的空间
substr.ch = NULL; //将substr置空
}
if( len==0 ) //若输入的子串的长度为0
{
substr.ch = NULL; //子串为空
substr.length = 0; //子串的长度为0
return 1; //求子串程序结束
}else{
substr.ch = ( char* )malloc( sizeof( char )*( len+1 )); //为子串动态分配存储空间
int i=pos; //i存储子串的开始位置
int j=0; //j为辅助变量
while( i<pos+len ) //当i还在子串中的位置时
{
substr.ch[j] = str.ch[i]; //将主串中的元素提取到新建的子串中
++i; //主串中的指针向后移一位
++j; //子串中的指针向后移一位
}
substr.ch[j] = '\0'; //子串建立完毕,以'\0'结束
substr.length = len; //子串的长度为len
return 1; //子串查询完毕
}
}
串清空操作
int clearstring( Str& str ) //待清空的串为str
{
if( str.ch ) //若str非空
{
free( str.ch ); //释放str的空间
str.ch = NULL; //将str置空
}
str.length = 0; //令str的长度为0
return 1;
}