zoukankan      html  css  js  c++  java
  • 【C语言学习笔记】字符串拼接的3种方法 .

    昨天晚上和@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 ", 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 != '') {  
    28.         *c++ = *a++;  
    29.     }  
    30.     while ((*c++ = *b++) != '') {  
    31.         ;  
    32.     }  
    33.     //注意,此时指针c已经指向拼接之后的字符串的结尾'' !   
    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 != '') {  
    48.         a++;  
    49.     }  
    50.     while ((*a++ = *b++) != '') {  
    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. }  
  • 相关阅读:
    四、面向对象分析和设计全流程概述
    三、三大核心特征-继承
    二、三大核心特征-多态
    [第三章]一、三大核心特征-封装
    四、抽象类
    三、接口
    二、对象
    [第二章]一、类
    六、面向对象的迷思
    五、面向对象的应用范围
  • 原文地址:https://www.cnblogs.com/wangluochong/p/4169727.html
Copyright © 2011-2022 走看看