新建头文件str.h
#ifndef _STR_H
#define _STR_H
typedef struct _STR{
char* ch;
int len;
}STR;
STR *NewStr(char* str);
void DestroyStr(STR* s);
void ClearStr(STR* s);
int StrCompare(STR* s,STR* t);
int StrConcat(STR* s,STR* t);
STR* SubStr(STR* s,int pos,int len);
#endif
新建str.c
#include<stdio.h>
#include<stdlib.h>
#include "str.h"
STR *NewStr(char* str){
STR* s=NULL;
int i;
s=(STR*)malloc(sizeof(STR));
if(s==NULL) return NULL;
for(i=0;str[i];i++){
s->ch=(char*)malloc((i+1)*sizeof(char));
}
if(s->ch==NULL){
free(s);
return NULL;
}
s->len=i;
while(i>=0){
s->ch[i]=str[i];
--i;
}
return s;
}
void DestroyStr(STR* s){
free(s->ch);
free(s);
}
void ClearStr(STR* s){
free(s->ch);
s->ch=NULL;
s->len=0;
}
int StrCompare(STR* s,STR* t){
int i;
for(i=0;(i<s->len)&&(i<t->len);i++ ){
if(s->ch[i]!=t->ch[i]){
return s->ch[i]-t->ch[i];
}
}
return s->len-t->len;
}
int StrConcat(STR* s,STR* t){
int i;
char* temp=NULL;
temp=(char*)malloc((s->len+t->len+1)*sizeof(char));
if(temp==NULL) return 0;
for(i=0;i<s->len;i++){
temp[i]=s->ch[i];
}
for(;i<s->len+t->len;i++){
temp[i]=t->ch[i-s->len];
}
ClearStr(s);
ClearStr(t);
s->ch=temp;
s->len=i;
return 1;
}
STR* SubStr(STR* s,int pos,int len){
STR* t=NULL;
if(pos<1 || pos > s->len || len < 0 || len>s->len-pos+1){
return NULL;
}
t=NewStr("");
ClearStr(t);
t->ch=(char*)malloc((len+1)*sizeof(char));
if(t->ch==NULL) return NULL;
t->len=len;
for(--len;len>=0;--len){
t->ch[len]=s->ch[pos-1+len];
}
t->ch[t->len]=0;
return t;
}
新建主函数文件main.c
#include "str.h"
#include<stdlib.h>
#include<stdio.h>
void main(){
int res;
STR* s=NewStr("hello");
STR* t=NULL;
printf("s=%s,len=%d\n",s->ch,s->len);
t=NewStr("cello");
printf("t=%s,len=%d\n",t->ch,t->len);
res=StrCompare(s,t);
if(res==0){
printf("s==t\n");
}else if (res>0){
printf("s>t\n");
}else{
printf("s<t\n");
}
}
输出
s=hello,len=5
t=cello,len=5
s>t