字符串复制

1328阅读 0评论2011-05-20 onezeroone
分类:C/C++

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>

  4. char* myStrdup(const char *str);

  5. int
  6. main(void)
  7. {
  8.     char *s = "Hello\n";    
  9.     char *r = myStrdup(s);
  10.     printf(r);
  11.     free(r);

  12.     return 0;
  13. }

  14. char*
  15. myStrdup(const char *str)
  16. {
  17.     char *new_str;
  18.     int len;

  19.     if (str) {
  20.         len = strlen(str) + 1;
  21.         new_str = (char *)malloc(sizeof(char)*len);
  22.         memcpy(new_str, str, len);
  23.     } else {
  24.         new_str = NULL;
  25.     }

  26.     return new_str;
  27. }


上一篇:字符串化小写
下一篇:字符串 复制前n个字符