(C)string的一些常用函数原型

来源:互联网 发布:linux ssh远程登录 编辑:程序博客网 时间:2024/05/13 13:24

1.int strlen(const char *s)

2.char * strdup(const char *s)

3.char* strcpy(char *tag,char *src)

4.char* strcat(char *str1,char *str2)

5.int strcmp(const char *str1,const char *str2)

一些实现方法(仅供参考):

1.

int mystrlen(const char *str)
{
if(NULL==str)
throw "Invalid argument(s)";


int len=0;
while(*str++!='\0')
{
len++;
}
return len;
}

2.

char* mystrdup(const char *str)
{
if(NULL==str)
throw "Invalid argument(s)";


char *p=NULL;
char *tag=NULL;
char *n=NULL;
const char *src=str;
int len=0;
len=mystrlen(n);
p=(char*)malloc(sizeof(char*)*len+1);
tag=p;
while(*str)
{
*p++=*str++;
}
*p='\0';
return tag;
}

3.
char* mystrcpy(char* tag,const char* src)
{
if((NULL==tag)||(NULL==src))
throw "Invalid argument(s)";
const char *s=src;
char *t=tag;
while(*s!='\0')
{
*t++=*s++;
}
*t='\0';
return tag;
}

4.
char* mystrcat(char *str1,const char *str2)
{
if((NULL==str1)||(NULL==str2))
throw "Invalid argument(s)";


char *s1=str1;
const char *s2=str2;
while(*s1) s1++;
while(*s2!='\0')
{
*s1++=*s2++;
}
*s1='\0';


return str1;
}

5.
int mystrcmp(const char *str1,const char *str2)
{
if((NULL==str1)||(NULL==str2))
throw "Invalid argument(s)";


while(*str1==*str2)
{
str1++;
str2++;
if(*str1=='\0'&&*str2=='\0')
return 0;
}
if(*str1>*str2)
return 1;
else
return -1;
}