C高级——DAY4

本文详细介绍了如何使用指针来重写C语言中的strcpy、strlen、strcat和strcmp四个字符串处理函数,展示了指针在内存操作中的应用。
摘要由CSDN通过智能技术生成

用指针改写strcpy函数

#include <stdio.h>
void my_strcpy(char* str,char* str1);
int main(int argc, const char *argv[])
{
    char str[]="hello";
    char str1[]="";
    my_strcpy(str ,str1);
    printf("%s\n",str1);
    
    return 0;
}

void my_strcpy(char* str,char* str1)
{
    int i=0;
    for(i;*(str+i)!='\0';i++){
        *(str1+i)=*(str+i);
    }
    *(str1+i)='\0';
    
}

用指针改写strlen函数

#include <stdio.h>
int my_strlen(char* str);
int main(int argc, const char *argv[])
{
    char str[]="asdfghhjkkl";
    int sum=0;
    sum=    my_strlen(str);
    printf("%d\n",sum);
    return 0;
}

int my_strlen(char* str){
    int count=0;
    char* ptr=str;
    for(int i=0;*(ptr+i)!='\0';i++)
    {   
        count ++;
    }
    return count;

}                                                       

 用指针改写strcat函数

#include <stdio.h>
  2 
  3 void my_strcat(char* str,char* str1);
  4 
  5 int main(int argc, const char *argv[])
  6 {   
  7     char str[30]="hello";
  8     char str1[30]="yes";
  9     my_strcat(str,str1);
 10     printf("%s\n",str);
 11     return 0;
 12 }
 13 
 14 void my_strcat(char* str,char* str1){
 15     char* ptr=NULL;
 16     ptr=str;
 17     char* ptr1=str1;
 18     int i=0,j=0;
 19     for(i=0;*(ptr+i)!='\0';i++){
 20     }
 21     for(j=0;*(ptr1+j)!='\0';j++){
 22             *(ptr+i+j)=*(ptr1+j);                                              
 23         }   
 24         *(ptr+i+j)='\0';
 25 
 26 }

 用指针改写函数strcmp

 

#include <stdio.h>

int my_strcmp(char* str,char* str1);


int main(int argc, const char *argv[])
{
    char str[]="hello";
    char str1[]="hello";
    printf("%d\n",my_strcmp(str,str1));
    return 0;
}

int my_strcmp(char* str,char* str1){
    int count=0;
    int i=0;
    for(i;*(str+i)!='\0';i++){
        if((*(str+i)-*(str1+i))!=0){
            count=*(str+i)-*(str1+i);
        }
    }
    if(*(str1+i)!='\0')
        count-=*(str1+i);
    return count;
}                                              

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值