实验E4:对字符串的操作(函数接口设计、字符串操作)

在这里插入图片描述

#include <iostream>
using namespace std;

int size(char*path);//计算路径长度 
char* filename(char*path);//获取文件名 
char* filepath(char *path);//获取文件所在目录 
char* refilecata(char*orig,char*now);//替换文件目录  orig是原来的文件路径,now是要替换成的目录 
char* connect(char*cata,char*file);//连接文件目录和文件名 

int main(){
	char *path="c:\\program files\\data.txt";
	return 0;
} 
int size(char*path){
	int cnt=0;
	while(path[cnt]!='\0'){
		cnt++;
	}
	return cnt;
}

char* filename(char*path){
	int cnt=size(path)-1;
	//从后往前查询
	while(path[cnt]!='\\'){
		cnt--;	//最后一个'\'的位置 因为这个位置之后是文件名字 
	}
	char *copy=(char*)malloc(size(path)-cnt);//开辟一片文件大小的指针 
	for(int i=cnt+1;i<size(path);i++){
		copy[i-cnt-1]=path[i];//读取文件名字 
	}
	copy[size(path)-cnt-1]='\0';//最后一位设置为 '\0'
	return copy;
}

char* filepath(char *path){
	int cnt=size(path)-1;//下标 
	while(path[cnt]!='\\'){
		cnt--;//找到最后一个'\' 
	}
	char*copy=(char*)malloc(cnt+2);	
	for(int i=0;i<=cnt;i++){
		copy[i]=path[i];//读入 
	}
	copy[cnt+1]='\0';
	return copy;
}
char* refilecata(char*orig,char*now){//替换文件目录  orig是原来的文件路径,now是要替换成的目录 
	char* name=filename(orig);//找到文件的名字 
	int cnt1=size(name);//文件名长度
	int cnt2=size(now);	//被替换成的目录长度
	char* copy=(char*)malloc(cnt1+cnt2+1);
	for(int i=0;i<cnt2;i++){
		copy[i]=now[i];	//读入目录 
	} 
	for(int i=0;i<cnt1;i++){
		copy[i+cnt2]=name[i];//读入文件名 
	}
	copy[cnt1+cnt2]='\0';
	return copy;

}

char *connect(char*cata,char*file){
	int cnt=size(cata)+size(file);
	bool flag=0;
	if(cata[size(cata)-1]!='\\'){
		flag=1;	//判断一下目录的最后一位是否为'\',并用flag标记一下 
		cnt++;
	} 
	char*copy=(char*)malloc(cnt+1);
	int jud=0;//数组下标 
	for(int i=0;i<size(cata);i++){
		copy[jud++]=cata[i];
	}
	if(flag){
		copy[jud++]='\\';//如果最后一位非'\',就加上 
	}
	for(int i=0;i<size(file);i++){
		copy[jud++]=file[i];
	}
	copy[jud]='\0';
	return copy;
	
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值