#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef int Status;
#define ERROR 0
#define OK 1
typedef struct {
char * ch; // 若是非空串,则按串长分配存储区,否则 ch 为 NULL
int length; // 串长度
}HString;
void ScanHString(HString& str){
// 读取HString类字符串
char chrstr[128];
scanf("%s", chrstr); //读取一个C字符串
str.length = strlen(chrstr); // 获得该字符串的长度
str.ch = (char *)malloc((str.length+1)*sizeof(char)); // 分配内存
strcpy(str.ch, chrstr); // 将字符串从C字符串拷贝到HString中
}
void PrintHString(HString str){
// 输出HString字符串
printf("%s", str.ch);
}
Status StrInsert(HString &S, int pos, HString T) { // 算法4.4
// 1≤pos≤StrLength(S)+1。在串S的第pos个字符之前插入串T。
int i;
if (pos < 1 || pos > S.length+1) // pos不合法
return ERROR;
if (T.length) { // T非空,则重新分配空间,插入T
if (!(S.ch = (char *)realloc(S.ch,(S.length+T.length+1)*sizeof(char))))
return ERROR;
for (i=S.length-1; i>=pos-1; --i) // 为插入T而腾出位置
S.ch[i+T.length] = S.ch[i];
for (i=0; i<T.length; i++) // 插入T
S.ch[pos-1+i] = T.ch[i];
S.length += T.length;
}
S.ch[S.length] = '\0'; // 注意字符结尾
return OK;
} // StrInsert
int main(){
HString stra, strb; // 定义两个字符串
int pos; // 定义插入的位置
ScanHString(stra); // 读取字符串
ScanHString(strb);
scanf("%d", &pos); // 读取位置
StrInsert(stra, pos, strb); // 字符串插入
PrintHString(stra); // 输出结果
return 0;
}
/**************************************************************
Problem: 2149
User: admin
Language: C++
Result: Accepted
Time:14 ms
Memory:1144 kb
****************************************************************/