加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

(原创)把两个字符串连接起来输出

(2012-09-04 11:34:08)
标签:

杂谈

分类: C语言

我们先后输入两个字符串,接着把两个字符串连接起来输出,比如先输入字符串a[5]:abcd,再输入字符串b[4]:efg,要求输出abcdefg。思路:可以把字符串b的值续接在字符串a的后面,接着输出a就可以了。

 

程序代码如下:

#include "stdafx.h"
#include <stdio.h>
#include <string.h>

 

void ADD(char *p,char *s,int i,int t)

 for(int m=0;m<t;m++)
 {
  *(p+i+m)=*(s++);

 }

*(p+i+m)='\0';

}

 

void main()
{
 char a[300];
 char b[300];
 int L1;
 int L2;
    gets(a);

 printf("the a is over\n");
 gets(b);
 L1=strlen(a);
 L2=strlen(b);
    printf("the b is over\n");


 printf("output the a add b\n");
 ADD(a,b,L1,L2);

 printf("%s\n",a);

}

我们定义子函数void ADD(char *p,char *s,int i,int t),在main函数中实例化:ADD(a,b,L1,L2);我们让a字符串的末尾加上b字符串,最后不要忘了,在末尾加上字符串结束标志‘\0,接着输出字符串a就可以了。

 

 

方法二:

我们可以用指针函数来创建子函数,顾名思义:也就是返回值是指针的函数,这时返回的是字符串a的指针,

程序代码如下:

#include "stdafx.h"
#include <stdio.h>
#include <string.h>

 

char* ADD(char *p,char *s,int i,int t)

 for(int m=0;m<t;m++)
 {
  *(p+i+m)=*(s++);

 }

*(p+i+m)='\0';

return p;

}

 

void main()
{
// char *ADD(char *p,char *s,int i,int t);
 char a[300];
 char b[300];
 int L1;
 int L2;
    gets(a);

 printf("the a is over\n");
 gets(b);
 L1=strlen(a);
 L2=strlen(b);
    printf("the b is over\n");


 printf("output the a add b\n");
// ADD(a,b,L1,L2);

 printf("%s\n", ADD(a,b,L1,L2));

 

}

其实由于我们的指针函数的形参是指针,这时直接对实参进行操作,为此这时a字符串已经发生变化, 

 printf("%s\n", ADD(a,b,L1,L2));与 printf("%s\n", a)是一样的。注意:指针直接对形参进行操作,这时的返回值其实是没有什么用的。

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有