数据结构顺序串创建插入计算长度等的基本运算
//顺序串的基本运算
#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");
}
运算结果图