C语言实现串

新建头文件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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

reg183

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值