码迷,mamicode.com
首页 > 编程语言 > 详细

【C语言学习笔记】字符串拼接的3种方法 .

时间:2014-12-17 17:55:47      阅读:951      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   ar   io   os   sp   for   strong   

昨天晚上和@buptpatriot讨论函数返回指针(malloc生成的)的问题,提到字符串拼接,做个总结。

 

 

  1. #include<stdio.h>   
  2. #include<stdlib.h>   
  3. #include<string.h>   
  4.   
  5. char *join1(char *, char*);  
  6. void join2(char *, char *);  
  7. char *join3(char *, char*);  
  8.   
  9. int main(void) {  
  10.     char a[4] = "abc"; // char *a = "abc"   
  11.     char b[4] = "def"; // char *b = "def"   
  12.   
  13.     char *c = join3(a, b);  
  14.     printf("Concatenated String is %s\n", c);  
  15.   
  16.     free(c);  
  17.     c = NULL;  
  18.   
  19.     return 0;  
  20. }  
  21.   
  22. /*方法一,不改变字符串a,b, 通过malloc,生成第三个字符串c, 返回局部指针变量*/  
  23. char *join1(char *a, char *b) {  
  24.     char *c = (char *) malloc(strlen(a) + strlen(b) + 1); //局部变量,用malloc申请内存   
  25.     if (c == NULL) exit (1);  
  26.     char *tempc = c; //把首地址存下来   
  27.     while (*a != ‘\0‘) {  
  28.         *c++ = *a++;  
  29.     }  
  30.     while ((*c++ = *b++) != ‘\0‘) {  
  31.         ;  
  32.     }  
  33.     //注意,此时指针c已经指向拼接之后的字符串的结尾‘\0‘ !   
  34.     return tempc;//返回值是局部malloc申请的指针变量,需在函数调用结束后free之   
  35. }  
  36.   
  37.   
  38. /*方法二,直接改掉字符串a,*/  
  39. void join2(char *a, char *b) {  
  40.     //注意,如果在main函数里a,b定义的是字符串常量(如下):   
  41.     //char *a = "abc";   
  42.     //char *b = "def";   
  43.     //那么join2是行不通的。   
  44.     //必须这样定义:   
  45.     //char a[4] = "abc";   
  46.     //char b[4] = "def";   
  47.     while (*a != ‘\0‘) {  
  48.         a++;  
  49.     }  
  50.     while ((*a++ = *b++) != ‘\0‘) {  
  51.         ;  
  52.     }  
  53. }  
  54.   
  55. /*方法三,调用C库函数,*/  
  56. char* join3(char *s1, char *s2)  
  57. {  
  58.     char *result = malloc(strlen(s1)+strlen(s2)+1);//+1 for the zero-terminator   
  59.     //in real code you would check for errors in malloc here   
  60.     if (result == NULL) exit (1);  
  61.   
  62.     strcpy(result, s1);  
  63.     strcat(result, s2);  
  64.   
  65.     return result;  
  66. }  

【C语言学习笔记】字符串拼接的3种方法 .

标签:style   blog   http   ar   io   os   sp   for   strong   

原文地址:http://www.cnblogs.com/wangluochong/p/4169727.html

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