串的基本操作!

#include<malloc.h>
#include<stdio.h>
using namespace std;
#define TRUE 1
#define FALSE 0
#define ERROR -1
#define MAXSIZE 10
#define NULL 0
typedef int Status;
/*
串的操作
注意:每个串默认开辟Len+1个单元,最后一个单元存储结束符'\0'
*/
typedef struct{
	char *ch;
	int length;
}String;
//生成一个值等于chars的串t
Status strAssign(String &t,char *chars){
	int len=0;
	char *tmp=chars;
	while(*tmp!='\0'){
		len++;
		tmp++;
	}
	if(len==0){
		//空串
		t.ch=(char*)malloc(sizeof(char));
		*(t.ch)='\0';t.length=0;
	}
	else{
		t.ch=(char*)malloc((len+1)*sizeof(char));//最后一个存‘\0’
		*(t.ch+len)='\0';t.length=len;
		char *tmp=t.ch;
		while((*chars)!='\0'){
			*tmp++=*chars++;			
		}
	}
	return TRUE;

}

//串长
int strLength(String &s){
	return s.length;
}

//比较字符串
int strCompare(String s,String t){
	if(s.length!=t.length)
		return FALSE;
	while(*s.ch!='\0'){
		if(*s.ch==*t.ch){
			s.ch++;t.ch++;
			continue;
		}
		else
			return *s.ch-*t.ch;
	}
	return 0;
}

//清除
Status clearString(String s){
	if(s.ch)
		free(s.ch);
		s.ch=NULL;
	return TRUE;
}

//连接字符串
Status concat(String &t,String s1,String s2){
	t.ch=(char*)malloc((s1.length+s2.length+1)*sizeof(char));
	t.length=s1.length+s2.length;
	*(t.ch+t.length)='\0';
	char *tmp=t.ch;
	while(*s1.ch!='\0'){
		*tmp=*s1.ch;
		tmp++;
		s1.ch++;
	}
	while(*s2.ch!='\0'){
		*tmp=*s2.ch;
		tmp++;
		s2.ch++;
	}
	return TRUE;
}

//截取字符串
String subString(String s,int pos,int len){
	if(pos<0||pos>len)
		return s;
	if(len+pos>s.length)
		return s;
	String subString;
	subString.ch=(char*)malloc((len+1)*sizeof(char));
	char *tmp=subString.ch;
	for(int i=0;i<len;i++){
		*(tmp+i)=*(s.ch+pos+i);
	}
	*(tmp+len)='\0';
	subString.length=len;
	return subString;
}

//输出
void print(String s){
	printf("串共长为%d\n",s.length);
	while(*(s.ch)!='\0'){
		printf("%c ",*(s.ch));
		s.ch++;
	}
	
}


void main(){
	char *test="i am a boy, my name is zxf!";
	String s;
	strAssign(s,test);
	print(s);
	printf("\n");
	String t;
	t.ch="i am b boy, my name is zxf!";
	t.length=27;
	printf("测试比较%d",strCompare(s,t));
	printf("\n");
	printf("测试连接\n");
	String con;
	concat(con,s,t);
	print(con);
	printf("\n");
	printf("测试截取字符串\n");
	String sub=subString(s,0,10);
	print(sub);

}

    功能比较简单,也可以试着去实现其他有关字符串的源码,也不讲求任何效率,就当是复习数据结构了,呵呵~~

你可能感兴趣的:(串的基本操作!)