数据结构顺序串创建插入计算长度等的基本运算

数据结构顺序串创建插入计算长度等的基本运算

//顺序串的基本运算
#include<stdio.h>
#define MAXSIZE 50

int StrLength(char* s)							//求串长
{
	int i = 0;
	while (s[i] != '\0')						//对串s中的字符个数进行技术知道遇见'\0'结束
		i++;
	return i;									///返回串s的长度
}

int StrCat(char s1[], char s2[])					//串连接
{
	int i, j, len1, len2;
	len1 = StrLength;
	len2 = StrLength;
	if (len1 + len2 > MAXSIZE - 1)				//若串s1存储空间不够,则返回错误代码
		return 0;
	i = 0; j = 0;
	while (s1[i] != '\0')
		i++;
	while (s2[j] != '\0')
		s1[i++] = s2[j++];						//将串s2的串值复制到串s1的串尾
	s1[i] = '\0';
	return 1;
}

int SubStr(char* s, char t[], int i, int len)	//求字串
{												//数组t返回串s中从第i个字符开始长度为len的子串(i<=i<=串长)
	int j, slen;
	slen = StrLength(s);
	if (i<1 || i>slen || len<0 || len>slen - i + 1)	//若给定参数不在范围之内,则返回错误代码
		return 0;
	for (j = 0; j < len; j++)
		t[j] = s[i + j - 1];
	t[j] = '\0';								//给字串t置结束
	return 1;
}

int StrCmp(char* s1, char* s2)
{
	int i = 0;
	while (s1[i] == s2[i] && s1[i] != '\0')		//两串对应位置上的字符进行比比较
		i++;
	return(s1[i] - s2[i]);						//返回比较值
}

int StrInsert(char* s, int i, char* t)
{											//将串t插入到串s的第i个字符位置,指针s和t指向存储字符串的字符数组
	char str[MAXSIZE];
	int j, k, len1, len2;
	len1 = StrLength(s);
	len2 = StrLength(t);
	if (i<0 || i>len1 + 1 || len1 + len2 > MAXSIZE - 1)
		return 0;							//参数不正确或超出范围
	k = i;
	for (j = 0; s[k] != '\0'; j++)
		str[j] = s[k++];
	str[j] = '\0';
	j = 0;
	while (t[j] != '\0')					//插入t到i的位置
		s[i++] = t[j++];
	j = 0;
	while (str[j] != '\0')					//暂存串str字串连接到s的t后面
		s[i++] = str[j++];
	s[i] = '\0';
	return 1;
}

void main()
{
	char x1[50] = "Abcdefghijk", x2[30] = "Mnopqrst", x3[20];
	printf("输出串x1:\n");
	puts(x1);
	printf("输出串x1的长度:%d\n", StrLength(x1));
	printf("输出串x2:\n");
	puts(x2);
	printf("输出串x2的长度:%d\n", StrLength(x2));
	if (StrCat(x1, x2))
	{
		printf("输出x1和x2链接后的串:\n");
		puts(x1);
	}
	else
		printf("连接失败!\n");
	if (SubStr(x1, x3, 5, 12))						//对x1求子串并存放到串x3
	{
		printf("输出串x1:\n");
		puts(x3);
	}
	else
		printf("出错了!\n");
	if (StrCmp(x1, x2) == 0)
		printf("x1,x2为空!\n");
	else
		printf("x2比x1大!\n");
	if (StrInsert(x2, 5, "AAAAA"))
	{
		printf("输出插入后的串x2:\n");
		puts(x2);
	}
	else
		printf("插入失败!\n");
}

运算结果图

 

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

惑星撞地球

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值