C语言:通过指针对字符串进行拼接

//

//  main.c

//  Pointer_stringcat

//

//  Created by ma c on 15/8/2.

//  Copyright (c) 2015年 bjsxt. All rights reserved.

//  要求:使用指针连接字符串,并将连接后的字符串输出到屏幕上。

 

#include <stdio.h>

#include<string.h>

void Pointer_stringcat(char *str1,const char *str2)

{

    while (*(str1++)!='\0');     //一直将指向str1的指针移到字符串的末尾

    str1--;

    while (*str2!='\0')

    {

        *(str1++) = *(str2++);  //开始连接

    }

    *str1 = '\0';               //连接完后,添加上字符串结束标识符

}

int main(int argc, const char * argv[])

{

    char s1[] = "hello ";     //这个是一个字符串变量,字符串的值可以被修改

    char *s2 = "world!";      //这个是一个字符串常量,不能更改字符串的值

    

    //char s1[] = "hello ";

    //char s2[] = "world!";

    char const *pt = s1;       //始终不改变pt的指向,pt一直指向s1的首地址

    

    Pointer_stringcat(s1,s2);  //调用自定义的字符串连接函数

    puts(pt);

    

    return 0;

}

 

posted @ 2015-08-02 19:21  XYQ全哥  阅读(3117)  评论(0编辑  收藏  举报