1、strcat函数的实现方法
(1)数组实现方法:
#include<stdio.h>
void strcat1(char s[],char t[])
{
int j=0,i=0;
while(s[i]!='/0')//判断是否为字符串s的末尾
i++;
while((s[i]=t[j])!='/0')
i++,j++;
}
main()//主函数,用于测试strcat函数的功能
{
char s[20]="i love ";//字符数组s应定义足够的长度,以便能装入连接后的字符串
char t[]="you";
strcat1(s,t);//调用字符串连接函数
printf("连接后的字符串为:%s/n",s);
}
(2)使用指针实现写法:
#include<stdio.h>
#include <assert.h>
char *strcat1(char *s,const char *t) //将源字符串t加const,表明其为输入参数
{
assert((s != NULL) && (t!= NULL) );//对源地址和目的地址加非0断言
while(*s)//判断是否为字符串s的末尾
s++;
while(*s++=*t++)//复制t中的字符串到s的末尾
;
return s; //为了实现链式连接将目的地址返回
}
main()//主函数,用于测试strcat函数的功能
{
char a[20]="i love ";//字符数组s应定义足够的长度,以便能装入连接后的字符串
char b[5]="you"; strcat1(a,b);//调用字符串连接函数
printf("连接后的字符串为:%s/n",a);
}
2、strcpy函数的实现方法
(1)数组实现方法
#include<stdio.h>
void strcpy1(char s[], char t[])
{
int i=0;
while((s[i]=t[i])!='/0')//将t中的字符串复制到s中
i++;
}
main()
{
char a[12]={"i love you"};
char b[6]={"love"};
strcpy1(a,b);
printf("复制后的字符串为:%s/n",a);
}
(2)指针实现方法
#include<stdio.h>
#include<assert.h>
char *strcpy1(char *s, const char *t)//将源字符串t加const,表明其为输入参数
{
//assert((s != NULL) && (t!= NULL) );//对源地址和目的地址加非0断言
char *p;
p=s;
while(*s++ = *t++);//将t中的字符串复制到s中
;
return p;//为了实现链式连接将目的地址返回
}
main()
{
char a[12]={"i love you"};
char b[6]={"love"};
strcpy1(a,b);
printf("复制后的字符串为:%s/n",a);
}
3、strlen函数的实现方法
(1)使用数组实现
#include<stdio.h>
int strlen1(char s[])
{
int i=0;
while(s[i]!='/0')//如果字符串中的字符不为结束字符,则加1
++i;
return i;
}
main()
{ char s[10]="iloveyou";
printf("字符串长度为:%d/n",strlen1(s));
}
(2)使用指针实现
#include<string.h>
#include<assert.h>
char strlen1(const char *s)
{
//assert( s != NULL ); //断言字符串地址非0
int i=0;
while(*s++)//如果字符串中的字符不为结束字符,则加1
++i;
return i;
}
main()
{ char s[10]="iloveyou";
printf("字符串长度为:%d/n",strlen1(s));
}
4、strcmp函数的实现方法
(1)使用数组实现
#include<stdio.h>
int strcmp1(char s[], char t[])
{
int i=0;
for(;s[i]==t[i];i++)
if(s[i]=='/0') return 0;
return s[i] - t[i];
}
main()
{
char a[10]="ab";
char b[10]="bc";
printf("字符串a比字符串b大%d/n",strcmp1(a,b));
}
(2)使用指针实现
#include<stdio.h>
int strcmp1(char *s, char *t)
{
for(;*s==*t;s++,t++)
if(*s=='/0') return 0;
return *s - *t;
}
main()
{
char a[10]="ab";
char b[10]="bc";
printf("字符串a比字符串b大%d/n",strcmp1(a,b));
}