一、strcpy()
代码示例:
#include <stdio.h>
/*
函数名称:char *strcpy(char *dest, char *src)
函数功能:将字符串src复制到dest中
函数参数: char *dest 目标字符串
char *src 源字符串
返回值: tmp 目标字符串的起始地址
*/
char *strcpy(char *dest, char *src)
{
char *tmp = dest;
if((dest == NULL)&&(src == NULL))
return NULL;
while(*dest++ = *src++);
return tmp;
}
int main(int argc, char *argv[])
{
char dest[10] = {0};
char src[8] = "abcdefg";
printf("%s\n", strcpy(dest, src));
return 0;
}
运行结果:
[root@VM-0-10-centos ~]# ./strcpy
abcdefg
二、strcat()
代码示例:
#include <stdio.h>
/*
函数名称:char *strcat(char *dest, char *src)
函数功能:将字符串src拼接到dest后面
函数参数: char *dest 目标字符串
char *src 源字符串
返回值: tmp 目标字符串的起始地址
*/
char *strcat(char *dest, char *src)
{
char *tmp = dest;
while(*dest)
dest++;
while((*dest++ = *src++) != '\0')
;
return tmp;
}
int main(int *argc, char *argv[])
{
char *dest = argv[1];
char *src = argv[2];
strcat(dest, src);
printf("%s\n", dest);
return 0;
}
运行结果:
[root@VM-0-10-centos ~]# ./strcat 123 abc
123abc
三、strstr()
代码示例:
#include <stdio.h>
/*
函数名称:char *strstr(char *str1, char *str2)
函数功能:判断str1中是否包含str2
函数参数: char *str1 源字符串
char *str2 子串
返回值: 如果包含子串,返回子串在源字符串中首次出现的地址
如果不包含,返回NULL
*/
char *strstr(char *str1, char *str2)
{
char *cp = str1;
char *s1 = NULL;
char *s2 = NULL;
if(!str1)
return NULL;
if(!str2)
return str1;
while(*cp)
{
s1 = cp;
s2 = str2;
while(*s2 && !(*s1 - *s2))
{
*s1++;
*s2++;
}
if (!*s2)
return (cp);
cp++;
}
return NULL;
}
int main(int argc, char *argv[])
{
char s1[10] = "abcdefghi";
char s2[4] = "deha";
if (strstr(s1, s2))
{
printf("s1 includes s2\n");
}
else if (strstr(s1, s2) == NULL)
{
printf("s1 not include s2\n");
}
return 0;
}
运行结果:
[root@VM-0-10-centos ~]# ./strstr
s1 not include s2