|
楼主 |
发表于 2022-4-16 21:07:04
|
显示全部楼层
#include<stdio.h>
#define MAXSIZE 100//顺序串存储空间的总分配量
typedef struct { //串结构定义
char ch[MAXSIZE];
int len;
}String;
int StringLength(String* S) {
int i = 0;
while (S->ch[i]!='\0') {
i++;
}
S->len = i;
return(S->len);
}
void CreateStr(String* S) {
//建立一个新串
gets (S->ch);
S->len = StringLength(S);
}
//求子串函数
int SubString(String* S, String* Sub, int pos, int len) {
int j;
if (pos<1 || pos>S->len || len<1 || len>S->len - pos + 1) {
Sub->len = 0;
printf("参数错误!\n");
return 0;
}
else {
for (j = 0; j < len; j++) {
Sub->ch[j] = S->ch[pos + j - 1];
}
Sub->ch[j] = '\0';
Sub->len = len;
return 1;
}
}
int StrInsert(String* S, String* S1, int pos) {
int k;
if (pos > S->len + 1) {
printf("插入位置失败!");
return 0;
}
else if (S->len + S1->len > MAXSIZE) {
printf("两串长度超过存储空间长度!");
return 0;
}
else {
for (k = S->len - 1; k > pos-1;k--)
S->ch[S1->len + k] = S->ch[k];
for (k = 0; k < S1->len; k++)
S->ch[pos + k - 1] = S1->ch[k];
S->len = S->len + S1->len;
S->ch[S->len] = '\0';
return 1;
}
}
main() {
String x, y;
String* S = &x, * Sub = &y;
int pos, len, flag = 0;
printf("请输入一个字符串:");
CreateStr(S);
printf("该串的值为:");
if (S->ch[0] == '\0') {
printf("空串!");
}
else {
puts(S->ch);
printf("该串的长度是:%d\n", S->len);
}
/*while (!flag) {
printf("请输入从第几个字符开始求子串:");
scanf_s("%d", &pos);
printf("请输入取出的子串的长度:");
scanf_s("%d", &len);
flag = SubString(S, Sub, pos, len);
if (flag) {
printf("所得的子串:");
puts(Sub->ch);
}
else {
printf("求子串失败!");
}
}*/
while (!flag) {
printf("请输入子串在主串插入的位置:");
scanf("%d", &pos);
printf("请输入子串:");
getchar();
CreateStr(Sub);
flag = StrInsert(S, Sub, pos);
if (flag) {
printf("所得的子串:");
puts(S->ch);
}
else {
printf("插入子串失败!");
}
}
}
这是前半部分· |
|