linux:字符串拷贝的五种方法:使用指针下标,指针变量加偏移量,指针变量自加等

字符串数组名做函数形参,会退化正指针变量,需要使用指针变量操作字符串

代码:

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>

void my_strcpy(char * src, char * dest)
{

/—字符串数组名做函数形参,会退化正指针变量,需要使用指针变量操作字符串—/

if 1 //方法一,指针下标操作字符

int i = 0;
while (src[i])
{
    dest[i] = src[i];
    i++;
}

#endif

if 0 //方法二,指针变量加偏移量

int i = 0;
while (*(src+i))
{
    *(dest+i) = *(src+i);
    i++;
} 

#endif

if 0 //方法三,指针变量自加

while (*src)
{
    *dest = *src;
    dest++;
    src++;
} 

#endif

if 0 //方法四,指针变量自加

while (*src)
{
    *dest++ = *src++;
}

#endif

if 0 //方法五,在while条件判断中做字符拷贝

while (*dest++ = *src++);  

#endif

return;

}

// char * serch_char(char * ch, int ch1)
// {
// while(*ch)
// {
// if(*ch == ch1) return ch;
// ch++;
// }
// return NULL;
// }

void main()
{
char ch[] = “hello world”;
printf(“%s\n”, ch);

char dest[128] = {0};
my_strcpy(ch, dest);
printf("%s\n", dest);

//printf("%s\n", ch);
//char ch1 = 'l';

// // while (*p)
// // {
// //     printf("%s\n",p);
// //     p++;
// // }

// p = serch_char(ch,ch1);
// // printf("%s\n", ch);
// printf("%s\n", p);

return;

}

结果:

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值