c语言strcpy、strcat、strlen 、字符逆序函数实现
#include <stdio.h>
//实现strlen函数
int Mystrlen(char *str)
{
int len = 0;
while(*str != '\0')
{
str++;
len++;
}
return len;
}
//实现strcpy函数
void Mystrcpy(char *des,const char *src)
{
if(NULL == des)
{
return ;
}
while(*src != '\0')
{
*des++ = *src++;
}
*des = '\0';
}
//实现strcat
char *Mystrcat(char *des,const char *src)
{
char *temp = NULL;
temp = des; //保存目的字符串首地址
while(*des++);
des--; //指向结束字符串
while(*des++ = *src++); //进行循环赋值
*des = '\0';
return temp;
}
int main(void)
{
int result = 0;
char *str = "hello";
char *str2 ="world";
result = Mystrlen(str);
printf("result = %d\n",result);
//测试二
char des[24]= {0};
Mystrcpy(des,str);
printf("des = %s\n",des);
//测试三
char *res = (char *)malloc(24);
res =Mystrcat(Mystrcat(res,str),str2);
printf("str = %s\n",res);
return 0;
}
字符逆序输出
#include <stdio.h>
#include <string.h>
//方式一
void Reverse_One(char *str)
{
int len = 0,i = 0;
len = strlen(str); //求出总长度
for(i = len -1;i >=0;i--)
{
printf("%c",str[i]);
}
printf("\n");
}
//方式二对折 交换
void Reverse_Two(char *str)
{
int len = 0,i = 0;
int temp = 0;
len = strlen(str);
for(i = 0;i < len/2;i++)
{
temp = str[i];
str[i] = str[len-i-1];
str[len-i-1] = temp;
}
printf("%s\n",str);
}
int main(void)
{
char str[12] = {0};
printf("please enter string:");
scanf("%s",str);
printf("-------------方式一-------------\n");
Reverse_One(str);
printf("-------------方式二-------------\n");
Reverse_Two(str);
return 0;
}