在C语言中对字符串的操作函数分两大类,一类是通过变量赋值的操作来实现,另一种是直接通过对内存的操作来实现,当然效率也是不一样的。
通过变量赋值的主要是str类:
strlen
strcpy
strcat
strcmp
strncpy
str
通过内存操作的主要是mem类:
memcpy
memcat
memset
memcmp
#include<iostream>
#include<assert.h>
using namespace std;
char* My_strcat(char *s,const char *Dest)
{
assert(Dest!=NULL && s!=NULL);//断言
char *ptem=s;
const char *ptemDest=Dest;
while(*ptem != '\0')
{
ptem++;
}
while(*ptemDest != '\0')
{
*ptem++ = *ptemDest++;
}
*ptem='\0';
return s;
}
char* My_strcpy(char* s,const char *s1)
{
assert(s !=NULL && s1!=NULL);
char *ptem=s;
const char *ptem1=s1;
while(*ptem1 != '\0')
{
*ptem++ = *ptem1++;
}
*ptem='\0';
return s;
}
int My_strcmp(const char *s,const char *s1)
{
assert( s != NULL && s1 != NULL);
const char *ptem=s;
const char *ptem1=s1;
while(*ptem != '\0' && *ptem1 != '\0')
{
if(*ptem > *ptem1)
return 1;
else if(*ptem < *ptem)
return -1;
ptem ++;
ptem1 ++;
}
if(*ptem != '\0' && *ptem1 == '\0')
return 1;
else if(*ptem == '\0' && *ptem1 != '\0')
return -1;
return 0;
}
void main()
{
char s1[]="Hello ";
char *s2="world";
int n=sizeof(s1)/sizeof(char);
int m=strlen(s1);
cout<<"字符串长度m="<<m<<endl;
cout<<"s1字符空间大小:"<<n<<endl;
strcat(s1,s2);
cout<<"系统函数调用s1="<<s1<<endl;
cout<<"--------------"<<endl;
My_strcat(s1,s2);
cout<<"编写函数实现s1="<<s1<<endl;
cout<<"**************"<<endl;
strcpy(s1,s2);
cout<<"系统函数调用s1="<<s1<<endl;
cout<<"--------------"<<endl;
My_strcpy(s1,s2);
cout<<"编写函数实现s1="<<s1<<endl;
cout<<"**************"<<endl;
int h=strcmp(s1,s2);
if(h == 1)
cout<<"result:s1>s2"<<endl;
else if(h==-1)
cout<<"result:s1<s2"<<endl;
cout <<"result:s1=s2"<<endl;
cout<<"--------------"<<endl;
int tem=My_strcmp(s1,s2);
if(tem == 1)
cout<<"result:s1>s2"<<endl;
else if(tem==-1)
cout<<"result:s1<s2"<<endl;
cout <<"result:s1=s2"<<endl;
}