码迷,mamicode.com
首页 > 其他好文 > 详细

strlen strcat strcpy strcmp 自己实现

时间:2018-06-12 23:32:22      阅读:348      评论:0      收藏:0      [点我收藏+]

标签:include   ++   str   malloc   strcpy   strcat   std   source   print   

strlen strcat strcpy strcmp 自己实现

strlen

include <stdio.h>
#include <string.h>
#include <assert.h>

size_t my_strlen(const char* str){
  assert(str != NULL);

  const char *tmp = str;

  size_t count = 0;
  while(*tmp++ != ‘\0‘){
    count++;
  }
  return count;
}

size_t my_strlen1(const char* str){
  assert(str != NULL);
  if(*str == 0){
    return 0;
  }else{
    return my_strlen1(str+1) + 1;
  }
}
int main(){
  char as[] = "hello C";
  printf("%ld\n",strlen(as));
  printf("%ld\n",my_strlen(as));
  printf("%ld\n",my_strlen1(as));
}

strcat

#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <malloc.h>

char* my_strcat(char* strd, const char* strs){
  assert(strd != NULL && strs != NULL);
  char *tmp = strd;
  while(*tmp++ != 0){}
  tmp--;
  while(*strs != 0){
    *(tmp++) = *strs++;
  }
  *tmp = ‘\0‘;
  return strd;
}

int main(){
  char s1[20] = "hello";
  char s2[] = " C";
  printf("strcat before s1 = %s\n", s1);
  char *str = my_strcat(s1,s2);
  printf("strcat after s1 = %s\n", s1);
  printf("strcat after str = %s\n", str);
}

strcpy

#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <malloc.h>

char* my_strcpy(char* strd, const char* strs){
  assert(NULL != strd && NULL != strs);
  char* tmp = strd;
  while(*strs != ‘\0‘){
    *tmp++ = *strs++;
  }
  *tmp = ‘\0‘;
  return strd;
}
int main(){
  char s1[20] = "hello";
  char s2[] = " wod";
  printf("strcpy before s1 = [%s]\n", s1);
  char *str = my_strcpy(s1,s2);
  printf("strcpy after s1 = [%s]\n", s1);
  printf("strcat after str = [%s]\n", str);
}

strlen strcat strcpy strcmp 自己实现

标签:include   ++   str   malloc   strcpy   strcat   std   source   print   

原文地址:https://www.cnblogs.com/xiaoshiwang/p/9175482.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!