⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ep5_8.cpp

📁 这里有大量的c语言习题呢!真的是题海哦
💻 CPP
字号:
/* 5.8   分别编写下列字符串处理函数
(1)char *strcat1 (char *s,const char *ct);
将串ct接到串s的后面,形成一个长串。【例5.2】以数组为参数,现用指针为参数。
(2)int strlen1(const char * s);
求字符串长度的函数,返回串长(不包括串结束符)。
(3)char * reverse (char *);
反置字符串s,即可将"break"成为"kaerb"。
(4)char * strchr( const char *cs,char c);
查找字符c在串cs中第一次出现的位置,返回指向该字符的指针,若没有出现则返回Null。
(5)char *strstr (const char *cs1,const char *cs2);
返回串cs2作为子串在cs1中第一次出现的位置,若没有出现则返回Null。
*/
#include<iostream>
using namespace std;
char* strcat1(char* s,const char* ct){
	char* st=s;
	while(*s) s++;//*S作为条件,等效*S!=0
	while(*s++=*ct++);
	return st;
}
int strlen1(const char* s){
	int i=0;
	while(*s++) i++;
	return i;
}
char* reverse (char* s){
	char temp,* temp1=s,* temp2=s;
	while(*temp2) temp2++;
	temp2--;//指针移回串尾
	while(temp2-temp1>0){//注意此处,从串两头的指针同时向中间移动,重合或交错时停止
		temp=*temp1;
		*temp1=*temp2;
		*temp2=temp;
		temp1++;
		temp2--;
	}
	return s;
}
char* strchr( const char*cs,char c){
	while(*cs!=c&&*cs) cs++;
	if(*cs==0) cs=NULL; //未找到返回NALL
	return (char*)cs;
}
char *strstr (const char *cs1,const char *cs2){
	char *temp,*temp1;
	while(*cs1){                         //只要主串还有字符未查,则继续
		while(*cs1!=*cs2&&*cs1) cs1++; //与子串第1个字符不符,主串查找位置后移一个字符
		//找到主串含有子串的第一个字符,或主串查完停止
		if(*cs1){	//主串含有子串的第一个字符,核对子串全部字符
			temp=(char*)cs1;
			temp1=(char*)cs2;
			while(*temp==*temp1&&*temp1){temp++;temp1++;};
			if(*temp1==0) return (char*)cs1;     //找到子串返回
			else cs1++;//本轮未找到,主串查找位置后移一个字符
		}
	}
	return NULL;                        //返回NALL
}

int main(){
	char a[40]="束明";
	char b[20]="是东南大学学生";
	char c[40]="Southeast University";
	char *cp;
	cout<<a<<endl;
	cout<<b<<endl;
	strcat1(a,b);
	cout<<"字符串连接后:"<<endl;
	cout<<a<<endl;//打印字符数组a
	cout<<"字符串长度为:"<<strlen1(a)<<endl;
	cout<<c<<endl;
	cp=strchr(c,'U');
	if(cp==NULL) cout<<"未找到"<<endl;
	else cout<<cp<<endl;//找到输出由该字符开始的剩余串
	cp=strchr(c,'A');
	if(cp==NULL) cout<<"未找到"<<endl;
	else cout<<cp<<endl;
	cout<<reverse(c)<<endl;
	cp=strstr(a,"是");
	if(cp!=NULL) cout<<cp<<endl;//找到输出由该字符串开始的剩余串
	else cout<<"未找到"<<endl;
	cp=strstr(a,"大学生");
	if(cp==NULL) cout<<"未找到"<<endl;
	else cout<<cp<<endl;
	return 0;
}
/*请教师解释为了函数的通用性,有些可不要返回值的函数,也保留返回值*/

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -