用StrAssign生成S1=’THIS IS A BOOK’,S2=’S’,S3=’ESE ARE’ 用SubString(S,S1,3,7)求出S=’IS IS A’ 用ConCat(T,S1,S2)求出T=’THIS IS A BOOKS’ 用Replace(T,S,S3)求出T=’THESE ARE BOOKS’(选做) 2. 用StrAssign生成U=’XYXYXYXYXYXY’,W=’w’ 用SubString(V,U,6,3)求出V=’YXY’ 用Replace(U,V,W)求出U=’XWXWXW’编写程序
时间: 2023-10-30 11:06:02 浏览: 29
好的,下面是一个用C语言实现的程序,可以完成这两个问题的要求:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define OK 1
#define ERROR 0
#define OVERFLOW -1
typedef struct {
char *ch;
int length;
} HString;
int StrAssign(HString *t, char *chars) {
/*生成一个其值等于串常量chars的串T*/
int i, j;
char *c;
if (t->ch) free(t->ch);/*释放T原有空间*/
for (i = 0, c = chars; c[i] != '\0'; i++);/*求chars的长度*/
if (!i) {
t->ch = NULL;
t->length = 0;
} else {
t->ch = (char *) malloc(i * sizeof(char));
if (!(t->ch))
exit(OVERFLOW);
for (j = 0; j < i; j++)
t->ch[j] = chars[j];
t->length = i;
}
return OK;
}
int SubString(HString *t, HString s, int pos, int len) {
/*用t返回串s的第pos个字符起长度为len的子串*/
int i;
if (pos < 1 || pos > s.length || len < 0 || pos + len - 1 > s.length)
return ERROR;
if (t->ch) free(t->ch);/*释放t原有空间*/
if (!len) {
t->ch = NULL;
t->length = 0;
} else {
t->ch = (char *) malloc(len * sizeof(char));
if (!(t->ch))
exit(OVERFLOW);
for (i = 0; i < len; i++)
t->ch[i] = s.ch[pos - 1 + i];
t->length = len;
}
return OK;
}
int ConCat(HString *t, HString s1, HString s2) {
/*用t返回由s1和s2联接而成的新串*/
int i;
if (t->ch) free(t->ch);/*释放t原有空间*/
t->ch = (char *) malloc((s1.length + s2.length) * sizeof(char));
if (!(t->ch))
exit(OVERFLOW);
for (i = 0; i < s1.length; i++)
t->ch[i] = s1.ch[i];
for (i = 0; i