字符串 复制前n个字符

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


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

  4. char *myStrndup(const char *str, size_t n);

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

  12.     return 0;
  13. }

  14. char *
  15. myStrndup(const char *str, size_t n)
  16. {
  17.     char *new_str;

  18.     if (str) {
  19.         new_str= (char *)malloc(sizeof(char)*(n+1));
  20.         strncpy(new_str, str, n);
  21.         new_str[n] = '\0';
  22.     } else {
  23.         new_str= NULL;
  24.     }

  25.     return new_str;
  26. }


上一篇:字符串复制
下一篇:字符串 填充前n个指定字符