串 堆分配存储 数据结构 C语言 严蔚敏

头文件

typedef struct{
	char *ch;
	int length;
}HString;
#define MAXSTRLEN  255
#define OK 1
#include
#include
#define TRUE 1
#define FALSE 0
#define ERROR 0
#define OVERFLOW -2
#include
using namespace std;

typedef int Status;

	Status StrAssign(HString &T,char *chars);
	Status SubString(HString &Sub,HString S,int pos,int len);
	Status Concat(HString &T,HString S1,HString S2);
	Status StrPrint(HString S);
	void InitalStr(HString &T);

 

函数

#include "com.h"
//初始化一个串
void InitalStr(HString &T){
	T.ch = NULL;
	T.length = 0;
}
Status Concat(HString &T,HString S1,HString S2){
  int i;
	if(T.ch)
		free(T.ch);
	if(!(T.ch=(char*)malloc((S1.length+S2.length)*sizeof(char))))    
		exit(OVERFLOW);
	for(i=0;iS.length||len<0||len>S.length-pos+1)
		return ERROR;
	if(Sub.ch)   free(Sub.ch);
	if(!len)            //长度为0,就全部置为0
	{
		Sub.ch=NULL;
      Sub.length=0;
	}
	else{
		Sub.ch=(char *)malloc(len*sizeof(char));   //分配空间
     if(!Sub.ch) exit(OVERFLOW);
	 for(i=0;i

主函数

#include "com.h"

int main(){
	int ch;
	int q=1,len,pos;
	char a[MAXSTRLEN],b[MAXSTRLEN];
	HString S1,S2,T,Sub;
   	InitalStr(T);
	InitalStr(S1);
	InitalStr(S2);
	InitalStr(Sub);
cout << "请输入主串S1" << endl;    
	cin >> a ;
	StrAssign(S1, a);


  cout<>ch;
	switch(ch){

	case 1:
       cout << "请输入要和主串S1连接的S2" << endl;    
    	cin >> b;
    	StrAssign(S2, b);
		  if (Concat(T,S1,S2))	
		   {
		      cout<<"连接成功后串为:";
		       StrPrint(T);
		  
		  }
	      else
	        	cout << "串连接失败" << endl;
	     break;

	case 2:
	       cout << "请输入求子串的pos和len的值"<> pos>> len;
        	if (SubString(Sub,S1,pos,len))
			{
	        	cout << "输出子串Sub:";
	    	     StrPrint(Sub);
			}
	      else
	    	    cout << "求子串失败!" << endl;
           break;
	 

	default:q=0;	break;
	
	}
	}	return 0;
}

结果

串 堆分配存储 数据结构 C语言 严蔚敏_第1张图片

你可能感兴趣的:(数据结构)