用c语言实现串的连接截断长度,数据结构之串结构的实现--定长结构(C语言)

学习参考: 严蔚敏: 《数据结构-C语言版》

基本操作

赋值操作

字符串连接

取长度

字符串比较

求子串

输出字符串

清空操作

代码实现

定长字符串结构定义

typedef struct

{

char str[MAXSIZE+1];

int length;

}String,* pStr;

赋值操作

int strAssign(pStr s, char* ch)

{

char* c = ch;

int i = 0;

s->length = 0;

while(*c && s->lengthstr[s->length] = *c;

++c;

s->length++;

}

s->str[s->length+1] = '\0';

return 0;

}

字符串连接

int canCat(pStr s, pStr s1, pStr s2)

{

int i = 0;

if(!s)

return 0;

s->length = 0;

if(s1->length+s2->length < MAXSIZE) // 不截断

{

while(s1->str[i] != '\0')

{

s->str[i] = s1->str[i];

i++;

}

i = 0;

while (s2->str[i] != '\0')

{

s->str[s1->length+i] = s2->str[i];

++i;

}

s->length = s1->length + s2->length;

}

else if(s1->length + s2->length > MAXSIZE) // 截断S2

{

printf(".....\n");

while(s1->str[i] != '\0')

{

s->str[i] = s1->str[i];

++i;

}

s->length = s1->length;

i = 0;

while( s->lengthstr[s1->length+i] = s2->str[i];

s->length++;

i++;

}

}

else// 截断S1或s=s1

{

while(s->length < MAXSIZE)

{

s->str[s->length] = s1->str[s->length];

s->length++;

}

}

s->str[s->length+1] = '\0';

return 1;

}

取长度

int getLength(pStr s)

{

if(!s)

return -1;

return s->length;

}

字符串比较

int strCompare(pStr s1, pStr s2)

{

int i = 0;

for(i=0; ilength && ilength; ++i)

{

if(s1->str[i] != s2->str[i])

return s1->str[i] - s2->str[i];

}

return s1->length - s2->length;

}

求子串

int subString(pStr sub, pStr s, int pos, int len)

{

int i = 0;

if(pos<1 || pos>s->length || pos+len>s->length || len<1)

return 0;

sub->length = 0;

while(istr[i] = s->str[pos+i];

++i;

}

sub->length = i;

sub->str[sub->length+1] = '\0';

return 1;

}

输出字符串

int clearString(pStr s)

{

if(s->length ==0 ||!s)

return 0;

s->length = 0;

return 1;

}

清空操作

int display(pStr s)

{

int i = 0;

printf("... shuchu...\n");

if(!s || s->length==0)

return 0;

while(s->str[i]!='\0')

{

printf("%c", s->str[i]);

++i;

}

printf("\n");

return 1;

}

测试代码

#include #include "String.h"

int main()

{

String s, s1, s2;

strAssign(&s, "Hello world");

printf("%d..\n", s.length);

display(&s);

strAssign(&s1, "my string");

strAssign(&s2, "my students");

canCat(&s, &s1, &s2);

display(&s);

printf("%d...\n", getLength(&s));

subString(&s, &s1, 3, 6);

display(&s);

printf("%d...%d\n", getLength(&s), s.length);

clearString(&s);

display(&s);

return 0;

}

写在最后

文章记录本人学习所得, 如有所错误, 欢迎留言指出交流, 大神请键盘下留人 ! ! !

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值