快捷搜索: 王者荣耀 脱发

字符串堆分配存储:插入操作

补全字符串堆分配存储的插入操作StrInsert

#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include <string.h>
#define OK 1
#define ERROR 0
#define MAXLEN 100
typedef struct {
	char *ch;
	int len;
} HString;
void Print(HString S) {
	int i;
	for(i=0; i<S.len; i++)
		printf("%c",S.ch[i]);
	printf("
");
}
int  StrAssign(HString *S,char *str) {
	int i;
	if(!S->ch)
		free(S->ch);
	for(i=0; str[i]!=; i++);
	if(i==0) {
		S->ch=NULL;
		S->len=0;
	} else {
		S->len=i;
		if(!(S->ch=(char *)malloc(i*sizeof(char))))
			return ERROR;
		for(i=0; i<S->len; i++)
			S->ch[i]=str[i];
	}
	return OK;
}
int StrInsert(HString *S,int pos,HString T) {
	int i;
	if(!S->ch||!T.ch)
	return ERROR;
	if(pos<=0||pos>S->len+1)
		return ERROR;
		S->ch=(char*)realloc(S->ch,S->len+T.len);
		for(i=S->len-1;i>=pos-1;i--){
			S->ch[i+T.len]=S->ch[i];
		}
		for(i=0;i<T.len;i++){
			S->ch[i+pos-1]=T.ch[i];
		}
		S->len=S->len+T.len;
		return OK;
	
}
int  main() {
	int pos,len,y;
	HString s,t;
	char chars[MAXLEN];
	int select;
	s.ch=NULL;
	s.len=0;
	t.ch=NULL;
	t.len=0;
	scanf("%s",chars);
	StrAssign(&s,chars);
	scanf("%s",chars);
	StrAssign(&t,chars);
	scanf("%d",&pos);
	y=StrInsert(&s,pos,t);
	if(y==1) {
		printf("Success!
");
		Print(s);
	} else
		printf("Failed!
");
}
经验分享 程序员 微信小程序 职场和发展