自行实现一些 C++ 自带的字符串操作函数

输出效果如下:
在这里插入图片描述
代码如下(自己定义 cstring 中的 strlen,strcpy,strcat,strcmp,strchr,strstr 函数并调用):

#include<iostream>
#include<cstring>
using namespace std;
//计算字符串的长度(元素个数)
int strlen0(const char *a){
    
    
	const char *p=a;
	while(*p!='\0') p++;
	return p-a;
}
//拷贝字符串
char *strcpy0(char *a,const char *b){
    
    
	char *p=a;
	while(*p++=*b++);// 0 不会终止,只有 '\0' 终止
	return a;
}
//将 b 添加在 a 的后面
char *strcat0(char *a,const char *b){
    
    
	char *p=a;
	while(*p!='\0') p++;
	while(*p++=*b++);
	return a;
}
//字符串的比较
int strcmp0(const char *a,const char *b){
    
    
	while(*a==*b){
    
    
		if(*a=='\0' && *b=='\0') return 0;
		*a++;*b++;
	}
	if(*a<*b) return -1;//'\0' 小于其它字符
	if(*a>*b) return 1;
}
//在字符串中查找字符
const char *strchr0(const char*a,char c){
    
    
	while(*a!=c && *a!='\0') a++;
	if(*a==c) return a;//找到了从字符 c 开始向后输出 a 直到结束
	return NULL;
}
//在字符串中查找字符串
const char *strstr0(char *str,char *sub){
    
    
	while(*str!='\0'){
    
    
		while(*str!=*sub && *str!='\0') str++;
		if(*str=='\0') return NULL;
		char *p=str,*q=sub;
		while(*q!='\0' && *q==*p){
    
    
			p++;q++;
		}
		if(*q=='\0') return str;
		str++;
	}
	return NULL;
}
//调用:
int main(){
    
    
	char a[100];
	cin.getline(a,100);
	int len=strlen0(a);
	char b[100];
	strcpy0(b,a);
	cout<<len<<endl;
	for(int i=0;i<len;i++) cout<<b[i];
	cout<<endl;
	strcat0(a,b);
	for(int i=0;i<strlen0(a);i++) cout<<a[i];
	cout<<endl;
	char c[100];
	cin.getline(c,100);
	if(strcmp0(c,a)) cout<<"c>a"<<endl;
	else cout<<"c<=a"<<endl;
	cout<<strchr0(c,'a')<<endl;
	char d[100];
	for(int i=5;i<10;i++) d[i-5]=c[i];
	cout<<strstr0(c,d)<<endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/interestingddd/article/details/115085004